In order to connect models and collections with the server-side of things, Backbone’s default approach is CRUD through RESTful Ajax requests. All the operations that read from or persist data to the server are delegated to a
sync() function that translates create, read, update, delete to PUT, GET, POST, DELETE through jQuery.
What I enjoy the most about Backbone is its simplicity, how it gives me what I need to be productive, no more no less. In the case of the storage layer, one only needs to override
sync in order to use an alternative. A popular example is Backbone.localStorage which, persists to the browser’s localStorage.
I have been part of building a team collaboration web application centered around XMPP at Riot AS. I will post details about the architecture on which the app is based, but in short we have completely replaced Ajax requests in favor of doing all client-server as well as client-client communications through XMPP. To do so, the need arose of a storage adapter to XMPP, and Backbone.xmpp was born.
Backbone.xmpp (GitHub)is a drop-in replacement for Backbone’s RESTful API, allowing models/collections to be persisted on XMPP Pub-Sub nodes. Naturally, Collections are mapped to nodes, whereas Models to the items of these nodes. Additionally, it listens for events on these nodes, receiving and propagating real-time updates of the models/collections from the server. Apart from Backbone, it depends on Strophe as well as my Strophe plugins for Pub-Sub.
For example, if you had a collection of type
BookCase consisting of models of type
Book, you could write:
1 2 3 4 5 6 7 8 9 10 11
- create a
BookCaseinstance by passing its
idand the Strophe
connectionin the options,
- fetch it from the server,
- add a book to the collection,
- and persist to Pub-Sub.
In your views you could be doing
1 2 3 4 5 6 7 8 9 10 11 12
Now, if somebody else added a book to the bookcase, you would promptly receive a notification, the
add event would be fired on your bookcase and the book’s view would appear to your browser.
Finally, if you do not want to receive push notifications on your models/collections or wish to craft your own events, you do not have to extend from
PubSubItem. In your own code, override
sync in both the model and the collection and provide an instance of
nodeon your collection. For instance:
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
You can then subscribe to the XMPP notifications elsewhere, say for example in your collection view:
1 2 3
There you go. Hope you will find this useful, will be looking forward to your contributions!