Socket. the io client is very elegant in event processing, which is similar to weboscket's limited javascript interface, but supports more custom events: varsocketio. connect (& amp; #39; http: // localhost: 9000/chat & amp; #39;); socket. on (& amp; #39; conn.
The socket. io client is very elegant in event processing, which is similar to weboscket's limited javascript interface, but supports more custom events:
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 can be used to decouple event Subscriber/event publishers. If the publisher does not know the subscriber, the subscriber only needs to register the subscriber and wait for the notification. EventBus is a simple, efficient, elegant, and good client architecture. Well, fortunately, javascrui itself supports passing functions as parameters, which is not too troublesome.
Building the simplest EventBus javascript library is not difficult:
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 );
},
// Simulate the event interface of 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.
With less than 40 lines of code, it provides event subscription, event cancellation, event broadcast/publishing, etc. Although simple, it has already met the simplest page-side EventBus model and can provide a full view.
The client uses the event bus code:
Javascript EventBus Example