I myself figure out a solution that also greatly improves the EventSource interface.
Server side . Do not send event type, just add an extra data field (so that I always use json). Therefore, instead of
event: eventName data: {mykey: 'myvalue'}
I am sending this from the server:
data: {mykey: 'myvalue', eventName: 'eventName'}
Client side . Now I can use the EventSource onmessage event callback, which is fired for every message that does not have an event type.
And for communication event listeners, I create a wrapper class with Backbone.Event functionality. Result:
// Server Sent Events (Event Source wrapper class) var MyEventSource = (function() { function MyEventSource(url) { var self = this; _.extend(this, Backbone.Events); this.source = new EventSource(url); this.source.onmessage = function(event) { var data, eventName; var data = JSON.parse(event.data); var eventName = data.eventName; delete data.eventName; // Now we can monitor all server sent events console.log('app.server.on ', eventName, '. Data: ', data); self.trigger(eventName, data); }; } return MyEventSource; })();
Now with this wrapper class I can easily extend the functionality, all events sent by the server can be easily tracked and thanks to the Backbone.Events extension, event handling in this class is much more powerful.
Usage example:
var source = new MyEventSource('url/of/source'); // Add event listener source.on('eventName', function(data) { console.log(data); }); // Fire a event (also very useful for testing and debugging!!) source.trigger('eventName', { mykey: 'myvalue' }); // Unbind event listener (very important for complex applications) source.off('eventName');
Now I have a component that is easy to process, extend, debug, and test.
tothemario
source share