Created
August 28, 2013 18:34
-
-
Save jgable/6369562 to your computer and use it in GitHub Desktop.
A WebSocket Based Backbone Model
This file contains 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 SocketsModel = Backbone.Model.extend({ | |
sockets: null, | |
autoListen: true, | |
// Mapping of channel to callback name (like events hash) | |
channels: function () { | |
var chans = {}; | |
chans["data"] = "onSocketData"; | |
chans["error"] = "onSocketDataError"; | |
return chans; | |
}, | |
initialize: function () { | |
// Keep track of socket subscriptions | |
this.subscriptions = {}; | |
if (this.autoListen) { | |
this.listen(); | |
} | |
}, | |
connectSockets: function () { | |
return socketsManager.connect(); | |
}, | |
listen: function () { | |
if (!this.sockets) { | |
this.sockets = this.connectSockets(); | |
} | |
this.subscribeChannels(); | |
}, | |
unlisten: function () { | |
this.unsubscribeChannels(); | |
}, | |
subscribeChannels: function () { | |
var self = this, | |
toSubscribe = _.clone(this.channels); | |
if (_.isFunction(this.channels)) { | |
toSubscribe = this.channels(); | |
} | |
// Call bindAll on all the subscription handlers | |
_.bindAll.apply(_, [this].concat(_.unique(_.values(toSubscribe)))); | |
_.each(toSubscribe, function (callbackName, channelName) { | |
self.subscribe(channelName, self[callbackName]); | |
}); | |
}, | |
unsubscribeChannels: function () { | |
var self = this; | |
_.each(this.subscriptions, function (subscription, name) { | |
self.unsubscribe(name); | |
}); | |
}, | |
subscribe: function (name, callback) { | |
this.unsubscribe(name); | |
this.subscriptions[name] = this.sockets.subscribe(name, callback); | |
// TODO: Success and error handling on subscription | |
}, | |
unsubscribe: function (name) { | |
if (this.subscriptions[name]) { | |
this.subscriptions[name].cancel(); | |
} | |
}, | |
parse: function (data) { | |
return data; | |
}, | |
onSocketData: function () { | |
var parsedData = this.parse.apply(this, arguments); | |
this.set(parsedData); | |
}, | |
onSocketDataError: function () { | |
this.trigger.apply(this, ["error"].concat(_.toArray(arguments))); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment