使用dojo.在对象、外部对象的方法中挂起和闭包

Using dojo.hitch and closures in an object, in a method of an outer object?

本文关键字:对象 挂起 闭包 方法 外部 dojo 使用      更新时间:2023-09-26

我有一个像这样使用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.loadargs.error都没有调用它们应该调用的方法。
我认为原因是dojo.hitch只在post请求返回后运行,当它应该在this引用外部communityWidgetClass对象之前运行。
但是,如果我之前调用dojo.hitch,则dataerror对象(我需要传递给xhrLoadxhrError)不存在。

我看了几个闭包的例子,包括几个月前我为一个更简单的情况写的一个,但是不知道如何将它们应用到这个情况。

我如何使args.load可以传递data(仅存在于XHR post请求的末尾)和svcType(仅存在于post请求之前)参数到communityWidgetClass.xhrLoad方法,并类似于args.error传递error参数到communityWidgetClass.xhrError ?

完全不使用xhrLoadxhrError方法可能更容易,只是将它们的主体移动到args.loadargs.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');
};