如何在 AngularJS 中停止 $broadcast 事件? [英] How to stop $broadcast events in AngularJS?

查看:29
本文介绍了如何在 AngularJS 中停止 $broadcast 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种内置的方法可以阻止 $broadcast 事件沿着作用域链向下传播?

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

$broadcast 事件传递的事件对象没有 stopPropagation 方法(如 $rootScope 上的文档 提到.)但是 这个合并的拉取请求 建议 $broadcast 事件可以对它们调用 stopPropagation.

The event object passed by a $broadcast event does not have a stopPropagation method (as the docs on $rootScope mention.) However this merged pull request suggest that $broadcast events can have stopPropagation called on them.

推荐答案

来自 angularJS 1.1.2 源代码的片段:

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

正如您所见,$broadcast 中的事件对象没有stopPropagation".

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

您可以使用 preventDefault 来代替 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"

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

这篇关于如何在 AngularJS 中停止 $broadcast 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆