AngularJs在回调中使用非注入服务

时间:2015-12-06 01:29:45

标签: angularjs callback

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

我正在使用angular-websocket通过互联网发送数据,我创建了一个名为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' ;
        });
}])

如评论中所述,我使Protocol for global能够在onOpen内使用它。由于$websocket调用了回调,因此this内的onOpen指针不是Protocol

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

1 个答案:

答案 0 :(得分:1)

我总是把它放到一个本地var中,以便我可以访问它而不用担心这种重新调整。

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)
}])