前几天在网上查阅了一些资料,并且自己尝试着手写了一下订阅发布模式。
其实可以发现订阅发布模式和自定义事件类似(但不同),原理是我们先定义一个事件类型并给一个callback,在后续执行这个callback。
var Works = (function () { function Works() { this.handlers = {} this.a = 'a' this.b = 'b' this.c = 'c' } Works.prototype = { constructor: Works, work: function (type, a, b, c) { this.a = a this.b = b this.c = c this.run(type) }, run: function (type) { if (this.handlers[type] instanceof Array) { var handlers = this.handlers[type]; // 遍历这个类型任务中所有的方法,并逐个运行 for (let i = 0; i < handlers.length; i++) { handlers[i](this.a, this.b, this.c) } } }, addListener: function (type, handler) { if (typeof this.handlers[type] == 'undefined') { this.handlers[type] = [] } this.handlers[type].push(handler) }, removeListener: function (type, handler) { if (!this.handlers[type]) return; var handlers = this.handlers[type] // 不传入handler,则解绑所有方法 if (!handler) { handlers = [] } else { // 遍历所有方法,找到相同并删除方法 for (let i = 0; i < handlers.length; i++) { if (handler === handlers[i]) { handlers.splice(i, 1) } } } } } return Works })() var work = new Works(); work.addListener('base', function (a, b, c) { console.log(a, b, c) }) work.addListener('sum', function (a, b, c) { console.log(a, b, c) }) work.work('base', 'e', 'f', 'g'); // e f g work.work('sum', 'ab', 'cd', 'ef'); // ab cd ef
后续我会通过学习JavaScript中不同的设计模式再来更新这一篇文章.
后续我会通过学习JavaScript中不同的设计模式再来更新这一篇文章.