[英]JQuery Promise .notify needs Closure…
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
. 当我观察的进步MyObject
我总是得到的值终值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);
}
You are doing .process
before returning the deferred, so by the time you attach progress listener, the notifications have already run. 您正在执行.process
然后返回延迟,因此在附加进度侦听器时,通知已经运行。
Try this: 尝试这个:
http://jsfiddle.net/Xe47R/2/ 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.