How to stop $broadcast events in AngularJS?

前端 未结 3 2052
南旧
南旧 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 21:00

    Snippets from angularJS 1.1.2 source code:

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

    As you can see event object in $broadcast not have "stopPropagation".

    Instead of stopPropagation you can use preventDefault in order to mark event as "not need to handle this event". This not stop event propagation but this will tell the children scopes: "not need to handle this event"

    Example: http://jsfiddle.net/C8EqT/1/

提交回复
热议问题