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)的。