使用dojo.在对象、外部对象的方法中挂起和闭包
Using dojo.hitch and closures in an object, in a method of an outer object?
我有一个像这样使用Dojo声明的对象("…"行表示我省略了我认为不需要理解问题的代码):
dojo.provide('communityWidgetClass');
dojo.declare('communityWidgetClass',null,{
...
postToTVService: function(svcType,postJson) {
try {
var svcPath;
switch (svcType) {
case this.SVC_REL: svcPath=insightConfig.relPath; break;
case this.SVC_MSG: svcPath=insightConfig.msgPath; break;
default: return;
}
this.consoleLog('communityWidget.postToTVService postJson',postJson);
this.startLoadingResults();
var args={
url:insightConfig.proxyPath+svcPath,
postData:postJson,
handleAs:'json',
preventCache:true,
load:function(data){
dojo.hitch(this,'xhrLoad',data,svcType);
},
error:function(error){
dojo.hitch(this,'xhrError',error);
}
};
var deferred=dojo.xhrPost(args);
} catch(err) {
this.consoleError('communityWidget.postToTVService',err);
}
},
...
xhrError: function(error) {
this.consoleError('xhrError',error);
},
xhrLoad: function(data,svcType) {
this.consoleLog('xhrLoad svc:'+svcType,data);
this.endLoadingResults();
}
});
运行postToTVService
内部的dojo.xhrPost
调用并检索所需的数据。我可以在Firebug的"Net"选项卡中看到请求。
问题是args.load
和args.error
都没有调用它们应该调用的方法。
我认为原因是dojo.hitch
只在post请求返回后运行,当它应该在this
引用外部communityWidgetClass
对象之前运行。
但是,如果我之前调用dojo.hitch
,则data
和error
对象(我需要传递给xhrLoad
和xhrError
)不存在。
我看了几个闭包的例子,包括几个月前我为一个更简单的情况写的一个,但是不知道如何将它们应用到这个情况。
我如何使args.load
可以传递data
(仅存在于XHR post请求的末尾)和svcType
(仅存在于post请求之前)参数到communityWidgetClass.xhrLoad
方法,并类似于args.error
传递error
参数到communityWidgetClass.xhrError
?
完全不使用xhrLoad
和xhrError
方法可能更容易,只是将它们的主体移动到args.load
和args.error
中,但是这些方法在完成后会更大,我认为它们更容易阅读和维护作为args
对象之外的方法。
您需要在this
仍然具有预期值的范围内调用hitch
,而不是在它已经混乱的回调中。
var args={
…,
load: dojo.hitch(this, function(data) {
// in this function, `this` is bound correctly - so we can call
this.xhrLoad(data, svcType);
}),
// alternatively, just "hitch" the method when the arguments match
error: dojo.hitch(this,'xhrError');
};
相关文章:
- JavaScript执行暂时挂起页面
- 是定义的操作系统睡眠/挂起期间setTimeout的行为
- Chrome浏览器“;挂起”;同时在循环中执行AJAX请求
- fullcalendar在删除导致浏览器挂起的多个事件时速度较慢
- 应用将图表转换为图像的jqplot代码时Chrome挂起
- 如何在不使用Internet Explorer的情况下从未挂起的HTML文件执行程序
- MongoDB collection.find()查询挂起
- 使用子字符串方法时应用程序挂起的原因
- 如何在AngularJS中取消挂起的请求
- 从node.js应用程序调用Mongoose Model.save()时挂起
- Chrome,Safari在从本地存储读取时挂起,而Firefox很好
- IE 10 挂起 XMLHttpRequest 6 分钟,然后响应请求(使用 AngularJS 实现 CRSF)
- 挂起 JavaScript 键关闭事件
- JavaScript参数对象不起作用
- HERE 映射 JS API v3 集群提供程序挂起,添加许多数据点
- Ajax 调用挂起在 jQuery 中
- writeln img src将数据提交到外部系统-Firefox和IE挂起
- 在jQuery中,.state()如何确定一个承诺是挂起的、已解决的还是被拒绝的
- 为什么JavaScript中没有挂起回调函数
- 使用dojo.在对象、外部对象的方法中挂起和闭包