Skip to content

Instantly share code, notes, and snippets.

@dristic
Last active December 21, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dristic/6347570 to your computer and use it in GitHub Desktop.
Save dristic/6347570 to your computer and use it in GitHub Desktop.
Code snippets for integrating Backbone with PubNub via http://github.com/pubnub/backbone
var MyCollection = Backbone.PubNub.Collection.extend({
name: 'MyCollection',
pubnub: pubnub
});
<script src="http://cdn.pubnub.com/pubnub.min.js"></script>
<script src="/path/to/backbone-pubnub.min.js"></script>
var pubnub = PUBNUB.init({
publish_key: 'demo',
subscribe_key: 'demo'
});
var _ = require('underscore')._,
Backbone = require('backbone'),
pubnub = require('pubnub').init({
publish_key: 'demo',
subscribe_key: 'demo'
});
var MyCollection = Backbone.Collection.extend({
// Add business logic here
});
var myCollection = new MyCollection();
pubnub.subscribe({
channel: 'backbone-collection-MyCollection', // This is what is created internally by the framework
callback: function (message) {
if (data.method === 'create') {
myCollection.add(data.model);
} else if (data.method === 'update') {
myCollection.remove(data.model);
} else if (data.method === 'delete') {
var record = _.find(myCollection.models, function (record) {
return record.id === data.model.id;
});
if (record == null) {
console.log("Could not record: " + model.id);
}
var diff = _.difference(_.keys(record.attributes), _.keys(data.model));
_.each(diff, function(key) {
return record.unset(key);
});
return record.set(data.model, data.options);
}
}
});
// Now myCollection will always be up to date.
// Here you can provide some way (i.e. http.createServer) to get the data from the server.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment