// 发布事件 publish = function (key) { if (!eventList[key]) { returnfalse } let fns = eventList[key], args = Array.prototype.slice.call(arguments, 1) for (let i = 0; i < fns.length; i++) { fns[i].apply(this, args) } }
// 取消订阅 remove = function (key, fn) { if (!eventList[key]) { returnfalse } let fns = eventList[key] if (!fn) { fns.length = 0 return } for (let i = 0, len = fns.length; i < len; i++) { if (fns[i] === fn) { fns.splice(i, 1) } } }
return { subscribe, publish, remove } })()
接下来让我们一起验证一下吧:
1 2 3 4 5 6 7 8 9 10 11
Observer.subscribe('food', function (num) { console.log('我想吃香蕉', num) }) Observer.subscribe('food', function (n, m) { console.log('我想吃苹果', n, m) }) Observer.subscribe('food', function (m) { console.log('我想吃凤梨', m) })