【问题标题】:Page context in SignalR typescript clientSignalR typescript 客户端中的页面上下文
【发布时间】:2017-12-06 02:08:48
【问题描述】:

在 typescript SignalR 客户端中,我如何在从异步集线器事件或承诺返回期间访问类范围,例如:

Client.ts

class Client {
    private _elementId: string;

    constructor(elementId: string){
       this._elementId = elementId
    }

    $.connection.hub.start()
        .done(function () {
            $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
           })
        .fail((err) => {
            $("#" + this._elementId).html("Error occured"); 
           });

    // handlers - methods called by the SignalR Hub
    $.connection.myHub.client.notification = function (message) {
        $("#" + this._elementId).html(message);
    };

}

this 范围之上的startnotification 方法的承诺已丢失,因此我无法访问_elementId 成员变量。

【问题讨论】:

    标签: jquery typescript signalr


    【解决方案1】:

    您可以在done 处理程序上使用箭头函数() => {} 来维护与使用fail 处理程序类似的词法范围。这将允许this 在处理程序中引用类实例:

    class Client {
        private _elementId: string;
    
        constructor(elementId: string){
           this._elementId = elementId
        }
    
        $.connection.hub.start()
            .done(() => {
                $("#" + this._elementId).html("Connection Id" + $.connection.hub.id);
            })
            .fail((err) => {
                $("#" + this._elementId).html("Error occured"); 
            });
    
        // handlers - methods called by the SignalR Hub
        $.connection.myHub.client.notification = function (message) {
            $("#" + this._elementId).html(message);
        };
    
    }
    

    这是一个简单的example 正在运行。注意控制台中的消息。

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多