Skip to content

Instantly share code, notes, and snippets.

@ismasan
Last active November 12, 2023 11:50
Show Gist options
  • Save ismasan/299789 to your computer and use it in GitHub Desktop.
Save ismasan/299789 to your computer and use it in GitHub Desktop.
/* Ismael Celis 2010
Simplified WebSocket events dispatcher (no channels, no users)
var socket = new FancyWebSocket();
// bind to server events
socket.bind('some_event', function(data){
alert(data.name + ' says: ' + data.message)
});
// broadcast events to all connected users
socket.send( 'some_event', {name: 'ismael', message : 'Hello world'} );
*/
var FancyWebSocket = function(url){
var conn = new WebSocket(url);
var callbacks = {};
this.bind = function(event_name, callback){
callbacks[event_name] = callbacks[event_name] || [];
callbacks[event_name].push(callback);
return this;// chainable
};
this.send = function(event_name, event_data){
var payload = JSON.stringify({event:event_name, data: event_data});
conn.send( payload ); // <= send JSON data to socket server
return this;
};
// dispatch to the right handlers
conn.onmessage = function(evt){
var json = JSON.parse(evt.data)
dispatch(json.event, json.data)
};
conn.onclose = function(){dispatch('close',null)}
conn.onopen = function(){dispatch('open',null)}
var dispatch = function(event_name, message){
var chain = callbacks[event_name];
if(typeof chain == 'undefined') return; // no callbacks for this event
for(var i = 0; i < chain.length; i++){
chain[i]( message )
}
}
};
@frjufvjn
Copy link

Oh!! Very Useful!! Thanks a lot!!
In this situation I tried to use eventEmitter on the client side. This gist is going to be a great alternative.

@jackson-sandland
Copy link

Thanks! This is fantastic!

@pra-richardg-sportsbet
Copy link

Kind of like a duplex RPC. I like it.

@exapsy
Copy link

exapsy commented Jun 26, 2019

And women say small things cant bring happiness. This is great.

@NEMESYS43
Copy link

very nice this is just the thing I needed

@PrinceCEE
Copy link

Very helpful and perhaps could be the abstraction created by socket.io

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment