如何在AngularJS中停止$ broadcast事件?

时间:2013-03-14 21:43:32

标签: angularjs angularjs-scope

是否有内置的方法可以阻止$broadcast事件进入范围链?

$broadcast事件传递的事件对象没有stopPropagation方法(docs on $rootScope提及。)但是this merged pull request建议$broadcast个事件可以stopPropagation打电话给他们。

3 个答案:

答案 0 :(得分:43)

angularJS 1.1.2源代码片段:

$emit: function(name, args) {
    // ....
    event = {
        name: name,
        targetScope: scope,
        stopPropagation: function() {
            stopPropagation = true;
        },
        preventDefault: function() {
            event.defaultPrevented = true;
        },
        defaultPrevented: false
    },
    // ....
}

$broadcast: function(name, args) {
    // ...
    event = {
        name: name,
        targetScope: target,
        preventDefault: function() {
            event.defaultPrevented = true;
        },
        defaultPrevented: false
    },
    // ...
}

正如您所看到的,$ broadcast中的事件对象没有“stopPropagation”。

您可以使用preventDefault将事件标记为“不需要处理此事件”,而不是stopPropagation。这不会停止事件传播,但这会告诉孩子范围:“不需要处理此事件”

示例:http://jsfiddle.net/C8EqT/1/

答案 1 :(得分:7)

由于broadcast没有stopPropagation方法,你需要使用defaultPrevented属性,这在递归指令中是有意义的。

在这里看看这个plunker:Plunkr

$scope.$on('test', function(event) { if (!event.defaultPrevented) { event.defaultPrevented = true; console.log('Handle event here for the root node only.'); } });

答案 2 :(得分:1)

我为此目的实施了一个事件小偷:

.factory("stealEvent", [function () {

  /**
   * If event is already "default prevented", noop.
   * If event isn't "default prevented", executes callback.
   * If callback returns a truthy value or undefined,
   * stops event propagation if possible, and flags event as "default prevented".
   */
  return function (callback) {
    return function (event) {
      if (!event.defaultPrevented) {
        var stopEvent = callback.apply(null, arguments);
        if (typeof stopEvent === "undefined" || stopEvent) {
          event.stopPropagation && event.stopPropagation();
          event.preventDefault();
        }
      }
    };
  };

}]);

使用:

$scope.$on("AnyEvent", stealEvent(function (event, anyOtherParameter) {
  if ($scope.keepEvent) {
    // do some stuff with anyOtherParameter
    return true; // steal event
  } else {
    return false; // let event available for other listeners
  }
}));

$scope.$on("AnyOtherEvent", stealEvent(function (event, anyOtherParameter) {
  // do some stuff with anyOtherParameter, event stolen by default
}));