繁体   English   中英

监听示波器中的多个事件

[英]Listen to multiple events inside a scope

我有一个简单的工厂,当通过POST,PUT和DELETE调用完成广播时,会广播消息。 之后,在控制器内部,我将监听并执行与所有3个调用相同的一组动作。 我可以一步一步收听所有3个事件吗?

在工厂里

$http.method(something)
.then(response => $rootScope.$broadcast('putpostdelMSG', response)) * 3 lines

在控制器中(我有什么)

$scope.$on('putMsg', (e, putResp) => ....long function chain..)
$scope.$on('postMsg', (e, postResp) => ....long function chain..)
$scope.$on('delMsg', (e, delResp) => ....long function chain..)

在控制器中(我想要的)
$scope.$on('{putMsg,postMsg,delMsg}', (e, {putRes,postResp,delResp}) => ....long function chain..)

收听从这三种方法中的任何一种广播时,要完成的功能链都是相同的。 有什么办法可以缩短代码而不重复代码吗? 谢谢

如果您只需要一个中央事件处理程序,就可以了,但是我认为将关注点分开,调用不同的事件处理程序是可以的,只需调用相同的基础函数即可。

 var app = angular.module("app", []); app.controller("exampleController", function($rootScope, $scope) { $scope.Get = function() { $rootScope.$broadcast("receivedMsg", "get data", "GET"); } $scope.Post = function() { $rootScope.$broadcast("receivedMsg", "update data", "POST"); } $scope.$on("receivedMsg", function(e, response, requestMethod) { if (requestMethod === "GET") $scope.show = response else $scope.show = response }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="exampleController"> <button type='button' ng-click="Get()">GET</button> <button type='button' ng-click="Post()">POST</button> {{show}} </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM