JavaScript设计模式与DOM浏览器模式解析
按键游戏:观察者模式实现
我们以按键游戏为例,之前使用中介者模式实现,现在采用观察者模式,并且支持无限数量的玩家。
首先,对通用发布者对象的接口进行调整,使其更接近浏览器环境:
- 将 publish()
、 subscribe()
和 unsubscribe()
分别改为 fire()
、 on()
和 remove()
。
- 事件类型作为三个函数的第一个参数。
- 除了订阅者的函数外,还可以提供额外的上下文,以便回调方法使用 this
引用其自身对象。
新的发布者对象代码如下:
var publisher = {
subscribers: {
any: []
},
on: function (type, fn, context) {
type = type || 'any';
fn = typeof fn === "function" ? fn : context[fn];
if (typeof this.subscribers[type] === "undefined") {
this.subscribers[type] = [];
}
this.subs