I’ve written a short and incomplete example (for the sake of this question) that attempts to use jquery to sum the width of a group of images. I’m having some issues figuring out how to handle scope in complex OO javascript applications.
function imageContainer(){
this.selector = "img.inContainer";
this.width = function(){
var tmp = 0;
$(this.selector).each(function(){
// use load to preload images
$(this).load(function(){
// our 'this' pointer to the original object is long gone,
// so is it even possible to accumulate a sum without using
// globals? Ideally, I'd like to increment a temporary value
// that exists within the scope of this.width();
tmp+=$(this).width();
});
});
// I'm thinking that returning here is problematic, because our
// call to each() may not be complete?
return tmp;
}
this.construct = function(){
alert(this.width());
}
this.construct();
}
I’m not really looking for a hack around this issue, I’d like to know how this sort of thing should be done – in a way that doesn’t trash encapsulation. Am I missing something obvious?
Many thanks.
Welcome to ajax. Your doing a bunch of operations in parallel asynchronously. So you need to keep track of how many complete and fire a callback when all have completed.
Any asynchronous operation like
.loadrequires you to either block for 100s of ms or change your API to use callbacks.Rather then the
var that = thispattern you can also use$.proxyinstead.Since you have the construct of doing n ajax tasks before firing your callback you can generalize this with some sugar.
Notice here I really want to use
$.fn.reducebut it does not exist. It could have beenOn second thought this sugar does not make it any simpler, at least it looks more like LISP then C now.