我有可能影響一個視圖元素的多個$rootScope.$broadcast
事件。我想要有一個分層功能來決定哪個事件優先進行視圖。
我的問題是,我怎麼能聽$rootScope
編輯的所有事件$broadcast
?是否有某種事件攔截器?
我有可能影響一個視圖元素的多個$rootScope.$broadcast
事件。我想要有一個分層功能來決定哪個事件優先進行視圖。
我的問題是,我怎麼能聽$rootScope
編輯的所有事件$broadcast
?是否有某種事件攔截器?
你不能這樣做,那將是一種反模式。
相反,你應該創建處理事件的排放和處理的服務,所以你可以從那裏做這一切的邏輯:在你的代碼
events.onAll(function(name, data) {
console.log('Broadcasted event:', name, data);
});
events.broadcast('foo', data1);
events.broadcast('bar', data2);
這樣,你不僅會
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.broadcast
來廣播您想要從onAll
監聽器獲知的事件。
$ rootScope。$ broadcast將自動'廣播'該變量/對象的結果。當你需要另一端時,是監聽器 - $ rootScope。$ on。它看起來像這樣:
//broadcast
$rootScope.$broadcast('variableName');
//listener
$rootScope.$on('variableName', function(event, args){
//do whatever you want in here when 'variableName' is broadcasted
});
我在尋找同樣問題的解決方案。在我看來,你也在尋找cairp的解決方案https://github.com/angular/angular.js/issues/6043。
這樣做的好處是您可以將其留在開發中,而不需要將其包含在生產代碼中,而無需更改應用程序中的任何邏輯。
我會從鏈接,後人複製代碼,稍作調整(與角當前版本的工作):約$ provide.decorate
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;
});
});
更多信息:
[1 ] http://blog.xebia.com/extending-angularjs-services-with-the-decorate-method/
[2] https://docs.angularjs.org/api/auto/service/ $試圖幫助提供
嘿感謝,但我需要知道的是如何截獲_all_廣播事件。 – roscioli 2015-04-01 20:56:10
您可以在變量集合'$ rootScope。$ watchGroup(['var1','var2','var3'],function(event,args){do stuff})上設置一個監視;' – jadams 2015-04-28 20:19:03
watchGroup不會攔截廣播的事件,但是在範圍內的表達式,因此這是無關的 – floribon 2016-10-11 09:21:40