简体   繁体   中英

In AngularJS, why can $emit events can be canceled but not $broadcast events?

这是因为父母与子女之间的一对多关系吗?

$emit "Dispatches an event name upwards through the scope hierarchy", while $broadcast "Dispatches an event name downwards to all child scopes (and their children)"

Looking at the source code we can see that $emit has both event.stopPropagation() and event.preventDefault()

$emit: function(name, args) {
    var empty = [],
        namedListeners,
        scope = this,
        stopPropagation = false,
        event = {
          name: name,
          targetScope: scope,
          stopPropagation: function() {stopPropagation = true;},
          preventDefault: function() {
            event.defaultPrevented = true;
          },
          defaultPrevented: false
        },
// ...

while $broadcast only has event.preventDefault()

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

This leads me to believe that the mechnism simply relies on DOM bubbling : events travel up and can be prevented from propagating upward (with event.stopPropagation() ), but the is no mechanism to prevent propagating downward.

The only difference between the $brodcast and $emit is the $emit always looks for the bottom to the top hierarchy to find it's parent and logically there will be only one parent scope. Hence it can call stopPropagation anytime to cancel further propagation of the event.

Whereas the $brodcast works top to bottom and there will be chances for many siblings controllers listening for the event. For Example $rootscope.$brodcast may be listened by many sibling controllers and it is not possible to stopPropagation.

Ultimately the answer to your question is yes, presumably stopPropagation is not implemented for $brodcast because of one-to-many(siblings) issue. Check out this link for more understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM