yxfanxiao / yxfanxiao.github.io

My Blog Space
3 stars 0 forks source link

EventBus 消息代理 #12

Open yxfanxiao opened 8 years ago

yxfanxiao commented 8 years ago

消息处理器

1、对象A直接调用对象B的某个方法,实现交互逻辑。但是导致的问题是A和B紧密耦合,修改B可能导致A调用B的方法失效。

2、为了解决耦合导致的问题,我们可以设计成: 对象A生成消息 -> 将消息通知给一个消息处理器(Observable)-> 消息处理器将消息传递给B 具体的调用过程变成: A.emit(‘message’,data);
B.on(‘message’,function(data){});
请实现这一事件消息代理功能

function EventEmitter() {
    this.eventFunctionMap = {}
}

// 注册
EventEmitter.prototype.on = function(eventName, callback) {
    this.eventFunctionMap[eventName] = callback
}

// 触发
EventEmitter.prototype.emit = function(eventName, data) {
    this.eventFunctionMap[eventName].apply(this, data)
}

在实际项目中,我们采用了android的EventBus消息机制的思想,实现一个页面内的消息通信,来进行解耦。同时配合socket.io(websocket的一个库)进行多页面间的通信。