在输入回调范围时获取对闭包 dojo 对象的访问权限

Get access to closure dojo object when callback scope was entered

本文关键字:对象 dojo 访问 权限 访问权 闭包 回调 输入 范围 获取      更新时间:2023-09-26

我有一个 dojo 对象,我想重试连接到 Web 套接字。但是,与 Web 套接字的连接由回调函数触发。我尝试订阅一个topic以允许在不使用this的情况下重新连接。但是,如果类有两个或更多实例,它将获取 MyClass 所有实例上的所有订阅消息。有没有办法只让无法连接的原始实例获取订阅的消息?

// Dojo class
dojo.declare("MyClass", null, {
    constructor: function() {
        dojo.subscribe("WebSocketConnect", this, function() {
            this.DoConnect();
        });
    }, 
    DoConnect: function() {
        this.myWebSocket = new WebSocket('ws://192.0.0.1');
        // ウェブソケットは閉じたイベント
        this.myWebSocket.onclose = function () {
            // The this in this clousure is "myWebSocket"
            setTimeout(function() {
                dojo.publish("WebSocketConnect", [ ] );
            }, 5000);
        };
    }
}

注意:我正在从事的项目使用 dojo 1.4。很旧,但我无权升级它。

您不想连接到this的任何特殊原因?

当您发布或订阅时,它取决于用于标识"事件"的字符串 ID,如果可以使其对每个实例唯一,则可以阻止函数在所有实例上执行。

// Dojo class
dojo.declare("MyClass", null, {
uniqueID:"",
constructor: function() {
    this.uniqueID = <generate unique id>;
    dojo.subscribe("WebSocketConnect" + this.uniqueID, this, function() {
        this.DoConnect();
    });
}, 
DoConnect: function() {
    var self = this;
    this.myWebSocket = new WebSocket('ws://192.0.0.1');
    // ウェブソケットは閉じたイベント
    this.myWebSocket.onclose = function () {
        // The this in this clousure is "myWebSocket"
        setTimeout(function() {
            dojo.publish("WebSocketConnect" + self.uniqueID, [ ] );
        }, 5000);
    };
}

}

如何生成uniqueID取决于你,它可以像全局计数器一样简单,也可以使用某些逻辑来创建 GUID。只要它是独一无二的,任何事情都会起作用。

使用动态主题名称:

// Dojo class
define(['dijit/registry', 'dojo/_base/declare', 'dojo/topic'], function(registry, declare, topic) {
  declare("MyClass", null, {
      constructor: function() {
        var uniqId = registry.getUniqueId('WebSocketConnect'),
          doConnect = this._DoConnect;
        //for external use
        this.DoConnect = function() {
          doConnect(uniqId);
        }
        //from internal fail
        topic.subscribe("WebSocketConnect" + uniqId, this.DoConnect());
      },
      _DoConnect: function(uniqId) {
        this.myWebSocket = new WebSocket('ws://192.0.0.1');
        // ウェブソケットは閉じたイベント
        this.myWebSocket.onclose = function() {
          // The this in this clousure is "myWebSocket"
          setTimeout(function() {
            topic.publish("WebSocketConnect" + uniqId, []);
          }, 5000);
        };
      }
    }
  });
});

但最好是使用挂钩:

// Dojo class
define(['dojo/_base/declare'], function(declare) {
  declare("MyClass", null, {
      DoConnect: function() {
        this.myWebSocket = new WebSocket('ws://192.0.0.1');
        // ウェブソケットは閉じたイベント
        this.myWebSocket.onclose = lang.hitch(this, function() {
          setTimeout(lang.hitch(this, 'DoConnect'), 5000);
        });
      }
    }
  });
});