JQuery Promise.notify需要关闭.
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
,因此在附加进度侦听器时,通知已经运行。
试试这个:
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();
相关文章:
- 使用promise和mongoose对文档进行排序
- 测试Angular Service解决错误回调中的promise
- 节点协同与生成器和Promise并行流量控制
- 根据是否解析了 Promise 从函数返回值
- 将一个方法转换为promise:Nodejs
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- js promise没有正确关闭
- Angularjs使用“;这个“;promise内的关键字回调
- AngularJS和promise值在调用本地函数时的效果-未定义
- 在ES6 Promise中,我应该在解决/拒绝之前使用return吗
- 以同步方式获取Javascript Promise的值
- NodeJS和pg promise,捕获PostgreSQL异常
- AngularJS使用http进行promise处理
- Angular promise return"未定义的“;值.NET MVC
- Promise函数在.then之后未运行函数化
- 如何为javascript promise进行阻塞并返回解析结果
- 将其中一个异步方法重写为使用promise的方法
- 通过AngularJS promise下载一个文件
- 如何在AngularJS视图中使用promise(ng-show)
- JQuery Promise.notify需要关闭.