How to stop $broadcast events in AngularJS?

前端 未结 3 2024
南旧
南旧 2020-12-29 20:17

Is there a built in way to stop $broadcast events from going down the scope chain?

The event object passed by a $broadcast event does not h

3条回答
  •  天涯浪人
    2020-12-29 20:56

    I implemented an event thief for this purpose:

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

    To use:

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

提交回复
热议问题