1

I think I am having a problem with closure/scoping. When I observer the progress of MyObject i always get the value final value of i.

Example

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

Observable Object

    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);   
    }

Demo

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 に答える