I have an async call that, when it completes, I want to set a property on the parent.
Take the following class, cat:
var cat = function(){
this.isLoaded = false;
this.image = new Image();
this.image.onload = function(){
//how can I set the isLoaded variable above from here??
}
this.image.src = "...";
}
I want to be able to do:
var myCat = new cat();
if(myCat.isLoaded)
....
I cant seem to figure out how to set the isLoaded property above from within the onload. I can access it by just doing ‘isLoaded’ but I think I am accessing it by value, not reference, and thus cant change it.
This seems like an easy solution, I guess I lack the deeper understanding.
Thanks!
Inside the
onloadcallback,isLoadedisundefined, and if you set it, it will bewindow.isLoaded(essentially a global).The callback’s
thistoo points to animgelement, not its parent function. I made athatvariable that points to the outer function’sthis. Functions in functions have access to their outer function’s scope in JavaScript.jsFiddle.
Of course, the
setTimeout()is used for this example only. If you are loading an image, you should rely on callbacks, because the only other way to determine if the image has loaded is by polling – not a very good interface.You should provide a place to pass in a callback, so you can do…