收听范围内的多个事件

时间:2017-03-22 19:40:45

标签: javascript angularjs angularjs-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..)

当从3种方法中的任何一种方法收听广播时,要完成的功能链是相同的。有没有办法缩短而不重复代码?谢谢

1 个答案:

答案 0 :(得分:1)

如果你只需要一个中央事件处理程序,这就是它,但我认为要分开关注点,调用不同的事件处理程序是可以的,只需调用相同的底层函数。

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>

相关问题