9. var Faye = require('faye'),
server = new Faye.NodeAdapter({mount: '/'});
server.listen(8000);
var client = new Faye.Client('http://localhost:8000/');
client.subscribe('/messages', function(message) {
alert('Got a message: ' + message.text);
});
client.publish('/messages', {
text: 'Hello world'
});
1
2
3
Start a server
Create a client
Send messages
10. REST (Client->Server) FAYE (Broadcast)OPERATION
Using a REST-like scheme for Pub/Sub
GET /api/todos/ client.subscribe(‘/api/todos/’, ...)
Create POST /api/todos/ { method:“POST”, body: {...} }
Update PUT /api/todos/id { method:“PUT”, body: {...} }
Delete DELETE /api/todos/id { method:“DELETE”, body: {...} }
13. var LiveCollection = Backbone.Collection.extend({
constructor: function(models, options) {
...
this.subscription = fayeClient.subscribe(this.url, this.fayeEvent);
},
fayeEvent: function(message) {
var method = message.method;
var body = message.body;
switch(method) {
case 'POST':
this._createEvent(body);
break;
case 'PUT':
this._updateEvent(body);
break;
case 'DELETE':
this._removeEvent(body);
break;
...
}
},
Listening to events on the client (LiveCollection base class)
14. Beware! Here there be dragons!
3.
beer.
Views need to respond to non UI
changes to the collection.
Address in code.We recommend using Marionette
(http://marionettejs.com/)
Ordering of events isn’t always what
you’d expect.
Faye events can be received by the client before the REST
operation returns. Need to handle this situation in code.
You need to consider security for your
websockets.
We use Bayeux extensions to authenticate on handshake and
subscribe messages.
Those dodgy websockets...
Various approaches including awake from sleep detection,
application-level pings. Can discuss over beer.