js发布订阅简洁版

var event = {
    items: {},
    on: function (type, fn) {
        if (!this.items[type]) {
            this.items[type] = []
        }
        this.items[type].push(fn)
    },
    emit: function (type) {
        for (var i in this.items) {
            if (i == type) {
                this.items[type].forEach(fn => fn())
            }
        }
    },
    off: function (type) {
        if (type) {
            delete this.items[type]
        } else {
            this.items = {}
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/ckAng/p/12416691.html