views:

111

answers:

2

I'm writing an application in javascript and cannot figure it out how to access the variables declared in my function, inside this jquery parse. Inside I can access global variables, but I don't really want to create global vars for these values.

Basically I want to extract file names from an xml document in the simulationFiles variable. I check if the node attribute is equal with the simName and extract the two strings inside the xml elements, that part I think it's working.

How can I extract those xml elements and append them to local variables?

function CsvReader(simName) {
    this.initFileName = "somepath";
    this.eventsFileName = "somepath";
    $(simulationFiles).find('simulation').each(function() {
       if ($(this).attr("name") == simName) {
           initFileName += $(this).find("init").text();
           eventsFileName += $(this).find("events").text();
       }
    });
}   
+5  A: 

Maybe like this?

function CsvReader(simName) {
    this.initFileName = "somepath";
    this.eventsFileName = "somepath";
    var $self = this;
    $(simulationFiles).find('simulation').each(function() {
       if ($(this).attr("name") == simName) {
           $self.initFileName += $(this).find("init").text();
           $self.eventsFileName += $(this).find("events").text();
       }
    });
}
Cory Larson
Thx for the quick answer, but unfortunately that doesn't work. Actually I tried it too before, but inside the unnamed function the $self is reported as not defined by firebug.
sekmet64
It works like this! Sorry about that, when I saved the this to a variable I had a different error after this function call and when I debugged the debugger showed me that $self.initFileName is undefined inside, but actually it was working and and I got the result.Thanks very much!
sekmet64
Are your `this.initFileName` and `this.eventsFileName` supposed to be local to your function or to the entire page? Nm... saw your post a few seconds later. Glad it works!
Cory Larson
+2  A: 

I made a working demo (I changed it to use classes so it would work with HTML).

function CsvReader(simName) {
    this.initFileName = "somepath";
    this.eventsFileName = "somepath";
    var context = this;
    $(simulationFiles).find('simulation').each(function() {
       if ($(this).attr("name") == simName) {
           context.initFileName += $(this).find("init").text();
           context.eventsFileName += $(this).find("events").text();
       }
    });
}   
Matthew Flaschen
This method worked great, thx! Sorry but the debugger miss leaded me a bit and taught it wasn't working.
sekmet64