看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'}
]);