我有可能$rootScope.$broadcast影响一个视图元素的多个事件.我想有一个分层函数来决定哪个事件优先于影响视图.
我的问题是,我怎样才能听取所有$broadcast关于的事件$rootScope?有某种事件拦截器吗?
我正在为同样的问题寻找解决方案.通过https://github.com/angular/angular.js/issues/6043了解了caitp的解决方案,我相信这也是你所寻找的.
这样做的好处是,您可以将其保留在开发中,而不必将其包含在生产代码中,而无需更改应用程序中的任何逻辑.
我将复制链接中的代码,用于后代,稍作调整(以使用当前版本的角度):
app.config(function($provide) {
$provide.decorator("$rootScope", function($delegate) {
var Scope = $delegate.constructor;
var origBroadcast = Scope.prototype.$broadcast;
var origEmit = Scope.prototype.$emit;
Scope.prototype.$broadcast = function() {
console.log("$broadcast was called on $scope " + this.$id + " with arguments:",
arguments);
return origBroadcast.apply(this, arguments);
};
Scope.prototype.$emit = function() {
console.log("$emit was called on $scope " + this.$id + " with arguments:",
arguments);
return origEmit.apply(this, arguments);
};
return $delegate;
});
});
Run Code Online (Sandbox Code Playgroud)
有关更多信息$ provide.decorate:
[1] http://blog.xebia.com/extending-angularjs-services-with-the-decorate-method/
[2] https://docs.angularjs.org/api/auto/service/ $ provide
你不能真的这样做,那将是一种反模式.
相反,您应该创建一个处理事件发射和处理的服务,以便您可以从那里执行所有这些逻辑:
module.service('events', function($rootScope) {
var onAllCallbacks = [];
this.broadcast = function(name, data) {
$rootScope.$broadcast(name, data);
onAllCallbacks.forEach(function(cb) { cb(name, data); });
}
this.on = function(name, callback) {
$rootScope.$on(name, callback);
}
this.onAll = function(callback) {
onAllCallbacks.push(callback);
}
})
Run Code Online (Sandbox Code Playgroud)
然后在你的代码中
events.onAll(function(name, data) {
console.log('Broadcasted event:', name, data);
});
events.broadcast('foo', data1);
events.broadcast('bar', data2);
Run Code Online (Sandbox Code Playgroud)
这样,您只能用于events.broadcast从onAll侦听器广播您想要了解的事件.
| 归档时间: |
|
| 查看次数: |
3569 次 |
| 最近记录: |