[英]JQuery Promise .notify needs Closure…
我認為我在關閉/范圍方面有問題。 當我觀察的進步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
然后返回延遲,因此在附加進度偵聽器時,通知已經運行。
嘗試這個:
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.