Created
January 28, 2010 10:40
-
-
Save ismasan/288614 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 | |
/* Usage | |
-----------------------------------*/ | |
var socket = new WebSocketDispatcher('some_channel', 'some_user_token'); | |
// Bind to custom events emitted by the server | |
// You can bind more than one handler to the same event. Handlers will be run in the order you registered them. | |
socket.bind('some_custom_event', function(data){ | |
// jquery example here. | |
// data is any data you broadcast to open sockets from the server. It can be jSon. | |
$('div#content').append("<p>" + data.name + "</p>"); | |
}); | |
// Bind to standard WebSocket events in the same way | |
socket.bind('close', function('close', function(){ alert('Socket closed!') }); | |
// You can also send events to all clients if the server supports multicasting. | |
// This keeps event semantics and you can send custom events | |
socket.trigger('message_received', {'user' : 'Ismael'}); | |
/* The code | |
-----------------------------------*/ | |
var WebSocketDispatcher = function(channel, user_token){ | |
var URL = "ws://localhost:8080/"; | |
var conn = new WebSocket(URL + channel +"?token=" + user_token); | |
var callbacks = {}; | |
this.bind = function(event_name, callback){ | |
callbacks[event_name] = callbacks[event_name] || []; | |
callbacks[event_name].push(callback); | |
return this;//chainable | |
}; | |
this.trigger = function(event_name, data){ | |
var payload = JSON.stringify([event_name, data]); | |
console.log(payload); | |
conn.send(payload); | |
return this; | |
}; | |
this.send = function(msg){ | |
return this.trigger('message', msg); | |
}; | |
// dispatch to the right handler | |
// Expects socket data as json array in the format: | |
// ['Socket-some_message_name', {'my_own_data' : 'blah'}] | |
// The first element must be a hyphenated event name. The second one is your custom data | |
conn.onmessage = function(evt){ | |
var data = eval(evt.data); | |
var event_name = data[0].split('-')[1]; // message, other | |
dispatch(event_name, data[1]) | |
}; | |
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'){ | |
console.log('No callbacks for '+event_name); | |
return; | |
} | |
for(var i=0;i<chain.length;i++){ | |
chain[i](message) | |
} | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment