Javascript EventBus(事件总线)模拟socket.io中事件处理
socket.io客户端对事件处理相当优雅,和weboscket的有限的javascript接口差不多一致好看,但可以支持更多的自定义事件:
var socket = io.connect('http://localhost:9000/chat');
socket.on('connect', function() {
// your code here
});
socket.on('announcement', function(msg) {
// your code here ...
});
socket.on('nicknames', function(nicknames) {
// your code here ...
});
view rawgistfile1.jsThis Gist brought to you by GitHub.
使用了EventBus(事件总线)方式可以很好的处理事件订阅者/事件的发布者解耦,发布者不知道订阅者,订阅者只需要自身注册,等待通知便可。EventBus是一种简单,高效,优雅,良好的客户端架构方式。嗯,还好,javascritp本身支持函数作为参数进行传递,要不还是很麻烦的。
构建一个最简单的EventBus javascript库,也不难:
yongboy = {};
yongboy.eventbus = {
listeners : {
list : {},
add : function(event, fn) {
this.list[event] = fn;
},
remove : function(event) {
this.list[event] = null;
}
},
subscribe : function(event, fn) {
this.listeners.add(event, fn);
},
// 模拟socket.io client的事件接口
on : function(event, fn) {
this.subscribe(event, fn);
},
broadcast : function(event) {
if (!this.listeners.list[event])
return;
var funcHolder = this.listeners.list[event];
if (!funcHolder)
return;
funcHolder.apply(this, [].slice.call(arguments, 1));
},
unsubscribe : function(event) {
this.listeners.remove(event);
}
};
view rawyongboy.eventbus.jsThis Gist brought to you by GitHub.
简单不到40行代码,提供了事件订阅,事件取消,事件广播/发布等,虽简单,但已经满足最简单的页面端EventBus模型,可以一窥全貌了。
客户端使用事件总线代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Javascript EventBus Example</title>
<script type="text/javascript" src="../js/yongboy.eventbus.js"></script>
<script type="text/javascript">
var eventbus = yongboy.eventbus;
eventbus.on('myEvent', function() {
alert('Publish Message~');
});
eventbus.on('myEvent2', function() {
alert('Publish Message Again~');
});
eventbus.subscribe('myEvent3', function() {
alert('Publish Message 3rd Times~');
});
eventbus.on('myEvent4', function(msg) {
alert('Publish Message 4th Times with args : ' + msg);
});
eventbus.on('myEvent5', function(msg, id) {
alert('Publish Message 4th Times with args : ' + msg + " id : " + id);
});
function pubshMsg(event, args){
eventbus.broadcast(event, args);
}
function pubshMsg2(event){
eventbus.broadcast('myEvent5', 'EventBus Msg Here ..', 10);
}
</script>
</head>
<body>
<input type="button" value="Publish Message With myEvent" onClick="pubshMsg('myEvent')" /><br />
<input type="button" value="Publish Message With myEvent2" onClick="pubshMsg('myEvent2')" /><br />
<input type="button" value="Publish Message With myEvent3" onClick="pubshMsg('myEvent3')" /><br/>
<input type="button" value="Publish Message With myEvent4" onClick="pubshMsg('myEvent4', 'EventBus Msg Here ..')" /><br/>
<input type="button" value="Publish Message With myEvent5" onClick="pubshMsg2()" />
</body>
</html>
view raweventbus.htmlThis Gist brought to you by GitHub.
看着和socket.io的客户端使用方式有所类似,但socket.io的处理方式复杂多了,并且多了一些内置的事件,这里不过是简化了很多。
嗯,有空谈一谈JAVA是如何做到事件总线(EventBus)的。