AngularJSでsocket.ioを使用したい。私は次の工場を見つけました:
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);
}
});
})
}
};
そしてそれは次のようにコントローラーで使用されます:
function MyCtrl($scope, socket) {
socket.on('message', function(data) {
...
});
};
問題は、コントローラーにアクセスするたびに別のリスナーが追加されるため、メッセージを受信すると、そのメッセージが複数回処理されることです。
socket.ioをAngularJSと統合するためのより良い戦略は何でしょうか?
編集:私は工場で何も返さず、そこでリスニングを行ってから、コントローラーで$rootScope。$broadcastと$scope。$onを使用できることを知っていますが、それは良い解決策のようには見えません。
EDIT2:ファクトリに追加されました
init: function() {
socket.removeAllListeners();
}
そして、socket.ioを使用する各コントローラーの先頭で呼び出します。
まだ最善の解決策のようには感じていません。