1

我认为我在关闭/范围界定方面存在问题。当我观察我的进度时,MyObject我总是得到最终的价值i

例子

var a = new MyObject();
a.progress(function(msg){console.log(msg)}); // always prints 1000/1000

可观察对象

    function MyObject()
    {
       var this.dfd = $.Deferred();
      return this.dfd.promise();
    } 

    MyObject.prototype.aProcess = function()
        {
            var self = this;
            for (var i = 0; i < 1000; i++)
            {
                (function(i)
                {

                   self.notify("Updating " + (i+1) + "/" + 1000); 
                   // Bunch of Processes

                })(i);
            }
        }

    MyObject.prototype.notify = function(message)
    {
        console.log(message) // works fine
        this.dfd.notify(message);   
    }

演示

4

1 回答 1

1

您在返回延迟之前正在做.process,所以当您附加进度侦听器时,通知已经运行。

试试这个:

http://jsfiddle.net/Xe47R/2/

function MyObject() {
    this.dfd = $.Deferred();
    //Don't explicitly return an object, otherwise the class is useless.
};
MyObject.prototype.process = function() {
    //The closure was useless here
    for (var i = 0; i < 1000; i++) {
        this.notify("Updating " + (i + 1) + "/" + 1000);
    }
};
MyObject.prototype.notify = function(message) {
    //Remove console.log from here to avoid confusion
    this.dfd.notify(message);
}
var a = new MyObject();
a.dfd.promise().progress(function(msg) {
    console.log(msg)
}); // always prints 1000/1000
a.process();​
于 2012-08-24T10:54:30.107 回答