Reputation: 1809
var sc = new stuCore();
function stuCore() {
this.readyPages = [];
this.once = true;
var self = this;
// gets called asynchronously
this.doPrepPage = function (page){
if(self.once == true){
// still gets executed every time, assignment fails
self.once = false;
doSomeStuffOnce();
}
};
this.addReadyPage = function (pageid) {
console.log("readypage called");
this.readyPages.push(pageid);
if (!$.inArray(pageid, self.readyPages) != -1) {
this.doPrepPage(pageid);
}
};
}
why does this assignment fail? I thought I knew the basics of js, but I'm stumped by this. And furthermore what would be a possible solution? call a constructor first and set the variable there?
EDIT: gets called like this in some other script:
sc.addReadyPage(self.id);
Upvotes: 3
Views: 239
Reputation: 4368
The jQuery.inArray
function will return the index in the containing array for the given value. Your script pushes pageid
into this.readyPages
before checking whether it exists in self.readyPages
. this.readyPages
and self.readyPages
are the same array reference, so the result will always be zero or greater, so the condition that calls doPrepPage
will never run.
You could try switching their order around:
this.addReadyPage = function (pageid) {
console.log("readypage called");
if ($.inArray(pageid, self.readyPages) != -1) {
this.readyPages.push(pageid);
this.doPrepPage(pageid);
}
};
(edit: Removed the additional !
, thanks @chumkiu)
Upvotes: 1
Reputation: 1422
If I understand correctly you're calling this.doPrepPage
as <insert variable name here>.doPrepPage
?
If this is the case then your var self
passes through to the anonymous function and is stored there, so everytime you call this.doPrepPage
it takes the local variable of self
.
Try setting self
to a global variable, this way it will permanently modify self
so each time this.doPrepPage
is called it uses the updated variable.
Upvotes: 0