关注前端知识,收集精彩博文,做技术的搬运工
观察者模式
1234567891011121314151617181920212223242526
class EventEmitter { constructor () { this.handles = {} } on (name, cb) { if (!this.handles) this.handles = {} if (!this.handles[name]) this.handles[name] = [] this.handles[name].push(cb) } emit (name, ...args) { if (this.handles[name]) { for (var i = 0; i < this.handles[name].length; i++) { this.handles[name][i](...args) } } }}let event = new EventEmitter()event.on('say', function(name) { console.log('hello, ' + name)})event.emit('say', 'lilei')