30

是否有一种内置方法可以阻止$broadcast事件沿着作用域链向下移动?

事件传递的事件对象$broadcast没有stopPropagation方法(如$rootScope 上的文档所述)。但是,此合并的拉取请求表明$broadcast事件可以stopPropagation调用它们。

4

3 回答 3

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/

于 2013-03-15T00:37:02.530 回答
7

由于广播没有 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.'); } });

于 2015-01-06T10:10:34.000 回答
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
}));
于 2016-02-11T17:52:43.557 回答