Skip to content

Instantly share code, notes, and snippets.

@andreisebastianc
Created March 19, 2013 19:43
Show Gist options
  • Save andreisebastianc/5199453 to your computer and use it in GitHub Desktop.
Save andreisebastianc/5199453 to your computer and use it in GitHub Desktop.
An approach on getting real time communication for backbone models without spamming channels for cometd. Can be easily updated to work for socket.io . Requires PubSub. The same approach can be used for sending information through channels.
//..
socket.subscribe('channel',function (data){
var data = JSON.parse(data.data);
// or you could search in a collection for the package you are looking for and handle the result
PubSub.publish('topic'+data.id, data);
});
(function (namespace, com) {
"use strict";
var RealtimeModel = {
/**
* @method
* @name realtimeBind
* @param {String} eventName
* @param {Function} callback
* @param {Object} context (optional): Object to interpret as this on callback
*/
realtimeBind: function (eventName, callback, context) {
this.bind(eventName, callback, context);
return this;
},
/**
* @method
* @name realtimeListen
* @param {String} namespace
*/
realtimeListen: function (namespace,id) {
var self = this;
this.realtimeSubscriptions = this.realtimeSubscriptions || {};
if (!this.realtimeSubscriptions[namespace]) {
var handleResult = function (topic,data) {
var args = [namespace];
args.push.apply(args, [data]);
self.trigger.apply(self, args);
if (data.errorCode) {
//handle fail here
}
};
// listens for a message on a given topic on PubSub and
// triggers the handle function
// manages the subscription so it can be removed later on
this.realtimeSubscriptions[namespace] = com.subscribe('topic'+this.id,handleResult);
}
return this;
},
/**
* unsubscribes all connections that were made by the realtime
* component
* @method
* @name cleanRealtimeSubscriptions
*/
cleanRealtimeSubscriptions: function () {
for (var subscription in this.realtimeSubscriptions) {
if (this.realtimeSubscriptions.hasOwnProperty(subscription)) {
com.unsubscribe(this.realtimeSubscriptions[subscription]);
}
}
return this;
}
};
return namespace.RealtimeModel = RealtimeModel;
}(window, PubSub));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment