Last active
November 12, 2023 11:50
-
-
Save ismasan/299789 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 ) | |
} | |
} | |
}; |
Thanks! This is fantastic!
Kind of like a duplex RPC. I like it.
And women say small things cant bring happiness. This is great.
very nice this is just the thing I needed
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
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.