简体   繁体   中英

Listen to multiple events inside a scope

I have a simple factory that broadcasts message when a POST, PUT and DELETE calls are done via it. After that inside a controller, I listen and perform a set of actions that are same for all the 3 calls. Can I listen to all 3 events in a single step?

In the factory,

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

In the controller (what I have)

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

In the controller (what I want)
$scope.$on('{putMsg,postMsg,delMsg}', (e, {putRes,postResp,delResp}) => ....long function chain..)

The function chain to be done is the same when listening to broadcast from any of the 3 methods. Is there any way to shorten and not repeat the code? Thank you

If you just need a central event handler, this it is, but I think to separate the concern, call different event handler is ok, just call the same underlying function.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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