在 AngularJS 中,我知道我可以将监听器附加到变量,如下所示:
$scope.$watch("variableName", listenerFunc);
我想知道是否可以查询变量以找出哪些函数已经在监听它。
具体来说,我想做如下的事情
if( listenerIsNotAlreadyAssigned("variableName",listenerFunc) ){
$scope.$watch("variableName", listenerFunc); // assign it
}
有没有办法在 Angular 中实现上面的代码?如果是这样,怎么办?
最佳答案
这是一种可能被认为是 hacky 的方法.. Demo here (click).
app.controller('myCtrl', function($scope) {
function checkWatchString(prop) {
var found = false;
angular.forEach($scope.$$watchers, function(item, i) {
if (item.exp === prop) { found = true; }
});
return found;
}
$scope.$watch('foo', function() {
});
console.log(checkWatchString('bar')); //false
console.log(checkWatchString('foo')); //true;
});
如果您存储对创建监视的引用,您将获得取消监视的函数引用。您可以采用显而易见的方法并手动跟踪此情况,并保持每个 watch 的取消功能可用。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.foo = '123';
var reg = {};
if (!reg.foo) {
reg.foo = $scope.$watch('foo', function() {
console.log('foo changed');
});
}
});
我使用以下服务制作了一个演示: http://jsbin.com/AbAwObE/4/edit
观看服务
app.factory('watchService', function() {
var watchService = function(prop, unset) {
if (!watchService[prop]) {
return false;
}
if (unset) {
watchService[prop]();
delete watchService[prop];
}
return true;
};
return watchService;
});
添加$watch
watchService[prop] = $scope.$watch(prop, function() {
++$scope.changeCount;
});
检查$watch
if (watchService(prop)) {
删除$watch
watchService(prop, true);
关于javascript - 如何在 AngularJS 中获取变量的监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243872/