了解Cranium.js代码

时间:2013-07-07 08:12:46

标签: javascript

我正在阅读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];
                        }

那就是:我理解if,我不知道的是花括号里面发生了什么。在我看来(但我可能是错的),如果左表达式为真,则没有任何反应,如果不是,则删除Cranium.Events.channels[topic]

我不明白的第二行是:

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

我不明白双减号。

任何评论都表示赞赏。

1 个答案:

答案 0 :(得分: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;中,--在应用Cranium.Events.eventNumber之前从events中减去1。所以,如果它之前是3,那么它将是2,因为它被添加到{{1}}。