Home In AngularJS, why can $emit events can be canceled but not $broadcast events?
Reply: 2

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

Calicoder Published in 2018-02-13 21:08:06Z

Is it because of the one-to-many relationship of parent-to-child scopes?

Kalyan Reply to 2018-02-13 23:36:58Z

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.

Sébastien Reply to 2018-02-13 22:56:57Z

$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 = [],
        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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30469 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO