我写了一个简短且不完整的例子(为了这个问题)试图使用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();
}
我并不是真的想要解决这个问题,我想知道应该这样做的事情 - 以一种不会破坏封装的方式。我错过了一些明显的东西吗?
非常感谢。
答案 0 :(得分:3)
function imageContainer() {
this.selector = "img.inContainer";
this.width = function(cb) {
var tmp = 0;
var len = this.length;
var count = 0;
$(this.selector).each(function() {
// use load to preload images
var that = this;
// load is ajax so it is async
$(this).load(function() {
tmp += $(that).width();
if (++count === len) {
// counted all.
cb(tmp);
}
});
});
};
this.construct = function(cb) {
this.width(function(data) {
alert(data);
});
};
this.construct();
}
欢迎来到ajax。你以异步方式并行执行大量操作。因此,您需要跟踪完成的数量,并在完成所有操作后触发回调。
任何异步操作(如.load
)都要求您阻止 100秒或更改您的API以使用回调。
而不是var that = this
模式,您也可以使用$.proxy
代替。
// load is ajax so it is async
$(this).load($.proxy(function() {
tmp += $(this).width();
if (++count === len) {
// counted all.
cb(tmp);
}
}, this));
由于你在触发回调之前有了做n个ajax任务的结构,你可以用一些糖来概括它。
this.width = function(cb) {
// map all images to deferred objects, when deferred objects are resolved
$.when($.makeArray($(this.selector).map(function() {
var def = $.Deferred();
$(this).load(function() {
def.resolve();
});
return def;
// then sum the widths and fire the callback.
}))).then($.proxy(function(data) {
var tmp = 0;
$(this.selector).each(function() {
tmp+=$(this).width();
});
cb(tmp);
}, this));
};
请注意,我真的想使用$.fn.reduce
,但它不存在。它可能是
// reduce the set of images to the sum of their widths.
cb($(this.selector).reduce(0, function(memo, key, val) {
return memo + $(this).width();
}));
第二个想法,这个糖并没有让它变得更简单,至少它现在看起来更像是LISP,而不是C。