本文介绍了改进这个 AngularJS 工厂以与 socket.io 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 AngularJS 中使用 socket.io.我找到了以下工厂:

I want to use socket.io in AngularJS.I found the following factory:

app.factory('socket', function ($rootScope) {
    var socket = io.connect();
    return {
        on: function (eventName, callback) {
            socket.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            })
        }
    };

它在控制器中使用,如:

and it is used in the controller like:

function MyCtrl($scope, socket) {
    socket.on('message', function(data) {
        ...
    });
};

问题在于每次访问控制器时都会添加另一个侦听器,因此在收到消息时会对其进行多次处理.

the problem is that each time the controller is visited another listener is added, so when a message is received it is handled multiple times.

将 socket.io 与 AngularJS 集成的更好策略是什么?

what can be a better strategy to integrate socket.io with AngularJS ?

我知道我不能在工厂返回任何东西并在那里进行监听,然后在控制器中使用 $rootScope.$broadcast 和 $scope.$on,但这看起来不是一个好的解决方案.

I know that I can return nothing in the factory and do the listening there, then use $rootScope.$broadcast and $scope.$on in the controllers, but it doesn't look like a good solution.

添加到工厂

init: function() {
            socket.removeAllListeners();
}

并在每个使用 socket.io 的控制器的开头调用它.

and call it at the beginning of each controller that use socket.io.

感觉仍然不是最好的解决方案.

still doesn't feel like the best solution.

推荐答案

每当控制器被销毁时移除套接字监听器.您需要像这样绑定 $destroy 事件:

Remove the socket listeners whenever the controller is destroyed.You will need to bind the $destroy event like this:

function MyCtrl($scope, socket) {
    socket.on('message', function(data) {
        ...
    });

    $scope.$on('$destroy', function (event) {
        socket.removeAllListeners();
        // or something like
        // socket.removeListener(this);
    });
};

有关详细信息,请查看 angularjs 文档.

For more information check the angularjs documentation.

这篇关于改进这个 AngularJS 工厂以与 socket.io 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 03:18