angularjs – 在$范围内侦听多个事件
发布时间:2020-12-17 08:05:46 所属栏目:安全 来源:网络整理
导读:我有一个指令,使用$ scope。$ on将某些函数绑定到本地范围。 可以在同一个调用中将同一个函数绑定到多个事件吗? 理想情况下,我可以这样做: app.directive('multipleSadness',function() { return { restrict: 'C',link: function(scope,elem,attrs) { sc
我有一个指令,使用$ scope。$ on将某些函数绑定到本地范围。
可以在同一个调用中将同一个函数绑定到多个事件吗? 理想情况下,我可以这样做: app.directive('multipleSadness',function() { return { restrict: 'C',link: function(scope,elem,attrs) { scope.$on('event:auth-loginRequired event:auth-loginSuccessful',function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); } }; }); 但这不行。与[‘event:auth-loginRequired’,’event:auth-loginConfirmed’]替换的逗号分隔事件名称字符串的示例也不会wrk。 这是什么工作: app.directive('multipleSadness',attrs) { scope.$on('event:auth-loginRequired',function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); scope.$on('event:auth-loginConfirmed',function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); } }; }); 但这不是理想的。 一次可以将多个事件绑定到同一个函数?
是。喜欢这个:
app.directive('multipleSadness',attrs) { function sameFunction(eventId) { console.log('Event: ' + eventId + '. The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks.'); } scope.$on('event:auth-loginRequired',function() {sameFunction('auth-loginRequired');}); scope.$on('event:auth-loginConfirmed',function () {sameFunction('auth-loginConfirmed');}); } }; }); 但只是因为你可以,不意味着你应该:)如果事件继续传播到另一个监听者,并且处理方式不一样,那么也许有一种情况要做。如果这将是唯一的听众,而不是你应该发出(或广播)相同的事件。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |