1

这是一段 index.html:

<div id="top">
    <div id="lvl1a">
    </div>
</div>

我已将两个 flightJS 组件附加到该结构。

一个用于顶部元素:

function top() {
    this.after('initialize', function () {
        console.log('[DEBUG] Top initialized.');

        this.on('broadcastEvent', function (e, data) {
            console.log("[DEBUG] Broadcast recived: " + data.message);
        });
        this.trigger('broadcastEvent', {
            message: "This is a broadcast message."
        });
    });
}

第二个是 lvl1a:

function lvl1a() {
    this.after('initialize', function () {
        console.log('[DEBUG] Lvl 1 a initialized.');

        this.on('broadcastEvent', function (e, data) {
            console.log("[DEBUG] Broadcast recived: " + data.message);
        });
    });
}

我的输出是:

[DEBUG] Top initialized.
[DEBUG] Broadcast recived: This is a broadcast message. 
[DEBUG] Lvl 1 a initialized. 

为什么事件没有传播到子节点?我怎样才能做到这一点?

编辑: 我发现这些事件是自下而上传播的。有没有可能改变它?

4

1 回答 1

2

Flight(实际上是 jQuery)使用标准的 DOM 事件传播模式——事件从子节点到父节点冒泡。

因此,为了接收来自所有孩子的通知,您应该将事件处理程序放在文档根元素 ( <html>) 或公共容器元素(如<body>.

试试这个

function lvl1a() {
    this.after('initialize', function () {
        console.log('[DEBUG] Lvl 1 a initialized.');

        $(document.body).on('broadcastEvent', function (e, data) {
            console.log("[DEBUG] Broadcast recived: " + data.message);
        });
    });
}
于 2014-09-09T19:03:44.287 回答