Skip to content

Instantly share code, notes, and snippets.

@adoc
Created October 31, 2014 00:16
Show Gist options
  • Save adoc/76c428a2e8a198875dcb to your computer and use it in GitHub Desktop.
Save adoc/76c428a2e8a198875dcb to your computer and use it in GitHub Desktop.
SocketioModel.js: Example of a backbone.js model enabled with socketio rather than "ajax". Very basic and not supporting the full backbone API.
var SocketioModel = Backbone.Model.extend({
//
constructor: function (attributes, options) {
options || (options = {});
if (options.socket) this.socket = options.socket;
if (options.controller) this.controller = options.controller;
if (options.model_id) this.id = options.model_id;
Backbone.Model.apply(this, arguments);
},
//
request: function (method, options) {
socketRequest(this.socket, method, {
ns: this.url(),
id: this.id
}, options);
},
//
sync: function (method, model, options) {
var self = this,
success;
if (method == "read") {
success = function (data) {
self.set(data);
if (options.success) {
options.success(model, null, options);
}
}
}
socketRequest(this.socket, method, {
ns: model.url(),
id: this.id,
data: this.changed
}, {
success: success
});
},
// Watch the model and receive a "change" event when updated.
watch: function (options) {
var self = this;
// Join on inintialize. This can probably be moved elsewhere.
socketRequest(this.socket, 'watch', {
id: this.id
},{
success: function(data) {
self.socket.on("change",
function (data) {
// console.log("Model change", data);
self.set(data);
}
);
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment