OO Javascript-适当的范围处理?
|
我已经写了一个简短且不完整的示例(出于这个问题),尝试使用jquery对一组图像的宽度求和。我在解决如何处理复杂的OO javascript应用程序中的范围时遇到了一些问题。
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();
}
我并不是真的在寻找解决此问题的方法,我想知道这种事情应该怎么做-不会浪费封装的方式。我是否缺少明显的东西?
非常感谢。
没有找到相关结果
已邀请:
1 个回复
盛虱
欢迎使用ajax。您异步并行执行一堆操作。因此,您需要跟踪完成的数量,并在所有完成后触发回调。 任何诸如“ 2”之类的异步操作都要求您阻塞100毫秒或更改API以使用回调。 而是使用
模式,也可以改用
。
由于您具有在触发回调之前执行n个ajax任务的构造,因此可以使用一些糖概括一下。
请注意,我确实要使用
,但它不存在。可能是
再次考虑,这种糖并没有使其变得更简单,至少现在看起来更像是LISP,然后是C。