如何停止在AngularJS $广播事件?(How to stop $broadcast event

2019-07-21 15:56发布

是否有一个内置的方法来阻止$broadcast从下降作用域链事件?

通过传递的事件对象$broadcast事件没有stopPropagation方法(如在$ rootScope文档提。)但是这个合并拉请求,建议$broadcast事件可以有stopPropagation叫上他们。

Answer 1:

从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
    },
    // ...
}

正如你可以看到在$广播事件对象没有“stopPropagation”。

相反stopPropagation的,你可以使用的preventDefault为了纪念事件为“不需要处理此事件”。 这不能阻止事件的传播,但是这会告诉孩子们的范围:“不需要处理此事件”

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



Answer 2:

由于广播不具备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.'); } });



Answer 3:

我实现了这个目的的事件贼:

.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
}));


文章来源: How to stop $broadcast events in AngularJS?