0

我正在阅读 Addy Osmani 的 Cranium.js ( https://gist.github.com/addyosmani/3769967 ) 代码,我无法理解两行 JavaScript 的作用。整个代码如下:

// Mix in to any object in order to provide it with custom events.
var Events = Cranium.Events = {
        channels: {},
        eventNumber: 0,
        trigger: function (events, data) {
            for (var topic in Cranium.Events.channels){
                if (Cranium.Events.channels.hasOwnProperty(topic)) {
                    if (topic.split("-")[0] == events){
                        Cranium.Events.channels[topic](data) !== false || delete Cranium.Events.channels[topic];
                    }
                }
            }
        },
        on: function (events, callback) {
            Cranium.Events.channels[events + --Cranium.Events.eventNumber] = callback;
        },
        off: function(topic) {
            delete Cranium.Events.channels[topic];
        }            
};

我不明白的第一行是:

if (topic.split("-")[0] == events){
                            Cranium.Events.channels[topic](data) !== false || delete Cranium.Events.channels[topic];
                        }

那就是:我理解如果,我不明白的是花括号内发生了什么。在我看来(但我可能是错的)如果左表达式为真,则不会发生任何事情,如果不是,他删除Cranium.Events.channels[topic].

我不明白的第二行是:

Cranium.Events.channels[events + --Cranium.Events.eventNumber] = callback;

我不明白双减号。

任何评论表示赞赏。

4

1 回答 1

3
if (topic.split("-")[0] == events){
    Cranium.Events.channels[topic](data) !== false || delete Cranium.Events.channels[topic];
}

是相同的

if (topic.split("-")[0] == events){
    if ( Cranium.Events.channels[topic](data) === false ) {
        delete Cranium.Events.channels[topic];
    }
}

并且在Cranium.Events.channels[events + --Cranium.Events.eventNumber] = callback;应用它之前--减去1 。Cranium.Events.eventNumber因此,如果之前为 3,则添加到events.

于 2013-07-07T08:17:25.620 回答