Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I figure out a solution myself, that also improves tremendously the EventSource interface.</p> <p><strong>Server side</strong>: Do not send the event type, just include an additional data field (having that I always use json). So instead of</p> <pre><code>event: eventName data: {mykey: 'myvalue'} </code></pre> <p>I send this from the server instead:</p> <pre><code>data: {mykey: 'myvalue', eventName: 'eventName'} </code></pre> <p><strong>Client side</strong>: Now I can use EventSource onmessage callback, that is fired on every message that does not have an event type.</p> <p>And for bind event listeners, I create a wrapper class with Backbone.Event functionality. The result:</p> <pre><code>// 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; })(); </code></pre> <p>Now with this wrapper class, I can easily extend the functionality, all server sent events can be easily monitored and thanks to extending Backbone.Events the event handling in this class is much more powerful.</p> <p>Usage example:</p> <pre><code>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'); </code></pre> <p>Now I have a component that is easy to handle, extend, debug and test.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload