我正在用angularjs工厂实现websockets。
angular.
module('core.socket').
factory('Socket', ['$rootScope', function($rootScope){
var ws;
var stack = [];
var onmessageDefer;
function socket(url){
ws = new WebSocket(url);
ws.onopen = function(event) {
for (i in stack) {
ws.send(stack[i]);
}
stack = [];
if (onmessageDefer) {
ws.onmessage = onmessageDefer;
onmessageDefer = null;
}
};
}
socket.prototype = {
send: function(data) {
data = JSON.stringify(data);
if (ws.readyState == 1) {
ws.send(data);
} else {
stack.push(data);
}
},
onmessage: function(callback) {
if (ws.readyState == 1) {
ws.onmessage = callback;
} else {
onmessageDefer = callback;
}
}
}
return socket;
}]);
Socket
工厂通过以下方式传递给控制器:
angular.
module('common').
controller('noteVBoxController', ['$scope', '$location','$element', 'Socket',
function($scope, $location, $element, Socket){
var self = this;
self.socket = new Socket("ws://192.168.225.59:8010/ws/");
$scope.submit = function(){
self.socket.send({
type: "place_note",
data: {
noteId: $scope.note.id
}
});
};
self.socket.onmessage(function(event) {
var data = JSON.parse(event.data);
$scope.note.top_note=data["message"];
});
}]);
如您所见,回调函数已传递给工厂,该函数无法使用当前的$ scope。请帮忙。
主要问题是,如果我将此控制器与多个指令元素一起使用,则最后一个元素的作用域仅在onmessage
函数内部可用。