[英]AngularJS: $watch – speeding things up
我一直在開發一個webapp,我必須在websocket上接收消息並進行更改。
基本上,我有類似的東西:
var socketService = angular.module('socketService');
socketService.factory('Listen', function () {
// connect etc.
socket.onmessage = function (msg) {
lastMsg = msg;
console.log(msg); // this is instant
}
return {
lastMsg: function () {
return lastMsg;
}
}
});
我在控制器內部有另一個模塊,我正在使用這個服務
var mainMod = angular.module('mainMod', ['socketService']);
// some more stuff
mainMod.controller('MainCtrl', function(Listen) {
$scope.$watch(Listen.lastMsg, function (newmsg, oldmsg) { // this is laggy
// do stuff here
});
});
問題是:我的$watch
在套接字上收到消息后不會觸發 。 如果我在console.log
中提供服務中的所有套接字消息,則會立即顯示日志,但是$ watch需要自己的甜蜜時間來觸發。 而且,這是非常不規則的 - 我沒有看到滯后的模式。
我認為這與Angular的嘀嗒聲有關 - 而且$ watch會在每個刻度上進行比較,但這會嚴重影響我的應用程序的性能。
一種可能的解決方法是使用$broadcast
,但我不希望這種方法。
我該怎么辦?
你的lastMsg
是一個原語,而且你正在監聽lastMsg
的$scope
,但是你沒有觸發$scope.$digest
(通常通過$scope.$apply
,但更安全, $timeout
)循環時它會發生變化。 為了讓你的$watch
觸發,你需要:
var socketService = angular.module('socketService');
socketService.factory('Listen', function ($timeout) {
var lastMsg;
// connect etc.
socket.onmessage = function (msg) {
$timeout(function(){ // acts as a $rootScope.$apply
lastMsg = msg;
console.log(msg);
});
}
return {
lastMsg: function () {
return lastMsg;
}
}
});
更好的方法是$rootScope.$emit
事件,這樣你就可以在發出事件時立即收到事件:
var socketService = angular.module('socketService');
socketService.factory('Listen', function ($rootScope) {
// connect etc.
socket.onmessage = function (msg) {
$rootScope.$emit('socket', msg);
}
return {
};
});
var mainMod = angular.module('mainMod', ['socketService']);
// some more stuff
mainMod.controller('MainCtrl', function(Listen) {
// when you inject Listen, your service singleton will be initialized
$scope.$on('socket', function(event, msg) {
// do stuff here
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.