问题描述
我可能有多个影响一个视图元素的 $ rootScope.$ broadcast
事件.我希望有一个层次函数来决定哪个事件优先于影响视图.
I have potentially multiple $rootScope.$broadcast
events affecting one view element. I would like to have a hierarchical function to decide which event takes precedence for effecting the view.
我的问题是,我该如何收听 $ rootScope
上所有 $ broadcast
的事件?有某种事件拦截器吗?
My question is, how can I listen to all events $broadcast
ed on the $rootScope
? Is there some kind of event interceptor?
推荐答案
您不能真正做到这一点,那将是一种反模式.
You cannot really do that, and that would be an anti-pattern.
相反,您应该创建一个处理事件发出和处理的服务,以便可以从那里开始所有这些逻辑:
Instead, you should create a service that handle events emission and processing so you can do all this logic from there:
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);
}
})
然后在您的代码中
events.onAll(function(name, data) {
console.log('Broadcasted event:', name, data);
});
events.broadcast('foo', data1);
events.broadcast('bar', data2);
这样,您将只使用 events.broadcast
广播要从 onAll
侦听器了解的事件.
That way you would only use events.broadcast
to broadcast events that you want to be aware of from the onAll
listener.
这篇关于如何在angular.js中拦截所有$ rootScope.$ broadcast事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!