JQuery Promise.notify需要关闭.

JQuery Promise .notify needs Closure...

本文关键字:Promise notify JQuery      更新时间:2023-09-26

我想我在闭包/作用域方面遇到了问题。当我观察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);   
    }

演示

在返回延迟之前,您正在执行.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();​