我从stackoverflow读了很多解决方案并且几乎有相同的答案,但仍然是“socket io在客户端angluarjs中发出多个时间事件”的问题我真的不明白。
这里我可以发出deletPhoto事件来删除照片和deletePhotoResponse事件来更新照片计数器,但是deletePhotoResponse会在每次事件调用时触发双倍的时间。
任何人都可以指导我吗?
HzSocket.js
(function () {
'use strict';
angular
.module("App")
.factory("HzSocket", ['$rootScope', '$cookies', '$location', 'HzServices',
function ($rootScope, $cookies, $location, HzServices) {
var socket = io.connect(HzServices.getAppUrl(), {
query: 'token=' + $cookies.get("hz-token")
});
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);
}
});
})
},
removeAllListeners: function (eventName) {
socket.removeAllListeners(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
}
};
}
]);
}());
PhotoCtrl.js
(function () {
'use strict';
function PhotoCtrl($rootScope, $scope, HzSocket) {
$scope.deletePhoto = function (photo, album, photoIndex, flag) {
HzSocket.emit("deletePhoto", data);
HzSocket.on("deletePhotoResponse", function (data) {
});
$scope.$on('$destroy', function (event) {
//HzSocket.removeAllListeners(this);
HzSocket.removeAllListeners('deletePhotoResponse');
});
}
};
$scope.$on('$destroy', function (event) {
HzSocket.removeAllListeners(event);
});
}
angular
.module("App")
.controller('PhotoCtrl', ['$rootScope', '$scope', 'HzSocket', PhotoCtrl]);
}());