全局订阅发布模式

var Event = (function () {
    var clientList = {},
        listen,
        trigger,
        remove
    listen = function (key, fn) {
        if (!clientList[key]) {
            clientList[key] = []
        }
        clientList[key].push(fn)
    }
    trigger = function () {
        var key = [].shift.apply(arguments),
            fns = clientList[key]
        if (!fns || !fns.length) {
            return
        }
        for (var i = 0, fn; fn = fns[i++];) {
            fn.apply(this, arguments)
        }
    }
    remove = function (key, fn) {
        var fns = clientList[key]
        if (!fns) {
            return
        }
        if (!fn) {
            fns && (fns.length = 0)
        } else {
            for (var l = fns.length - 1; l >= 0; l--) {
                if (fns[l] === fn) {
                    fns.splice(l, 1)
                }
            }
        }
    }
    return {
        listen: listen,
        trigger: trigger,
        remove: remove
    }
})()

Event.listen('88', function (data) {
    console.log(data, '88')
})
Event.trigger('88', 1232)
上一篇:理解闭包


下一篇:npx 使用方法