javascript 发布订阅

简单实现发布订阅

function Pubsub () {
    var events = {}
    this.on = function (event, fn) {
        events[event] = events[event] || []
        events[event].push(fn)
    }
    this.emit = function (event, data) {
        events[event].forEach(function(fn){
            fn(data)
        })
    }
    this.off = function (event, fn) {
        events[event].forEach(function(fn, i){
            events[event].splice(i, 1)
        })
    }
}

var pub = new Pubsub()
pub.emit('alert', 2)

你可能感兴趣的:(javascript 发布订阅)