【问题标题】:AngularJs using a non injected service inside callbacksAngularJs 在回调中使用非注入服务
【发布时间】:2015-12-06 01:29:44
【问题描述】:

我遇到了一个问题,我已经以一种讨厌的方式解决了,但我在这里提出它,看看是否有更好的方法。

我正在使用 angular-websocket 通过 Internet 发送数据,我创建了一个名为 Protocol 的简单服务,它使用 $websocket 和消息传递工作流。

这是Protocol 服务的简化版本:

app.service('Protocol', [ '$websocket',
function ($websocket) {
    this.variable = 'to be changed in event' ;

    this.connect = function() {
        this.ws = $websocket('ws://mydomain.org') ;

        this.ws.onOpen(function() {
            // when i'm here the this pointer is a $websocket, not Protocol
            // so i made Protocol a global variable to be able to use it here
            Protocol.variable = 'new value' ;
        });
}])

如评论中所述,我将协议设为全局以便能够在 onOpen 中使用它。由于回调是由$websocket 调用的,所以onOpen 中的this 指针不是Protocol

有没有更简洁的方法来更改this.variable 而无需添加任何全局?

【问题讨论】:

    标签: angularjs callback


    【解决方案1】:

    我总是把它放到一个本地变量中,这样我就可以访问它而不用担心这个重新范围。

    app.service('Protocol', [ '$websocket',
        function ($websocket) {
            this.variable = 'to be changed in event' ;
    
            this.connect = function() {
                var me = this;
    
                me.ws = $websocket('ws://mydomain.org') ;
    
                me.ws.onOpen(function() {
                // when i'm here the this pointer is a $websocket, not Protocol
                // so i made Protocol a global variable to be able to use it here
                me.variable = 'new value' ;
            });
    }])
    

    如果你不喜欢你也可以绑定你的函数

    app.service('Protocol', [ '$websocket',
        function ($websocket) {
            this.variable = 'to be changed in event' ;
    
            this.connect = (function() {
                this.ws = $websocket('ws://mydomain.org') ;
    
                this.ws.onOpen(function() {
                    // when i'm here the this pointer is a $websocket, not Protocol
                    // so i made Protocol a global variable to be able to use it here
                    this.variable = 'new value' ;
                });
            }).bind(this)
    }])
    

    【讨论】:

    • 第一种方法很明显,我喜欢它的源代码可维护性,第二种看起来更棘手。
    • 我同意第一种方法更可取,但在某些情况下需要绑定。当您需要嵌套回调时,绑定会变得非常混乱
    猜你喜欢
    • 1970-01-01
    • 2015-11-03
    • 2013-08-30
    • 2013-03-02
    • 2016-11-02
    • 2013-04-07
    • 2014-01-27
    • 2014-12-19
    • 2017-02-03
    相关资源
    最近更新 更多