0

onComplete结果:目前item.name总是rty,但应该是 (1/2): qwe, (2/2): rty。我知道这个问题可以通过使用闭包来解决,但不知道如何。

一点更新 http://jsfiddle.net/tJYem/

Items = function(){
    this.onProgress = function(current, total, item){};
    this.onComplete = function(){};
}

Items.prototype.add = function(items){

    var self = this;
    var i = 0, total = items.length;

    while(items.length){
        var item = items.shift();
        var img = new Image();

        // closure should be somewhere here...
        img.onload = function(){

            self.onProgress(++i, total, item);

            i == total && self.onComplete();

        }

        img.src = item.src;

    }

}


var items = new Items();

items.onProgress = function(current, total, item){
    console.log('(%d/%d) item `%s` loaded', current, total, item.name);
    // => (1/2) item `rty` loaded
    // => (2/2) item `rty` loaded
}

items.onComplete = function(){
    console.log('Loading items complete.')
}

items.add([
    {name: 'qwe', src: '../qwe.png'},
    {name: 'rty', src: '../rty.png'}
]);
4

2 回答 2

0
img.onload = (function(currentI) {
    // here currentI will stay with the value the i had in the moment of creating this handler
})(i)

另一件需要注意的事情是,在加载列表onComplete中的最后一个图像时触发逻辑处理程序,而不是在所有图像都已加载时触发。

于 2012-08-29T12:28:11.080 回答
0

您希望i由所有onload处理程序递增,因此不要为该变量创建闭包。否则,所有处理程序都会增加自己i的值,而不是共享值。此外,self与图像无关。但是,item每个处理程序应该不同:http: //jsfiddle.net/tJYem/1/

img.onload = (function(item){
    return function(){
        self.onProgress(++i, total, item);
        i == total && self.onComplete();
    }
})(item);
于 2012-08-29T12:42:55.227 回答