Last active
December 21, 2015 18:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MyCollection = Backbone.PubNub.Collection.extend({ | |
name: 'MyCollection', | |
pubnub: pubnub | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="http://cdn.pubnub.com/pubnub.min.js"></script> | |
<script src="/path/to/backbone-pubnub.min.js"></script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pubnub = PUBNUB.init({ | |
publish_key: 'demo', | |
subscribe_key: 'demo' | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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