sonarr-repo-only/UI/Mixins/backbone.signalr.mixin.js

66 lines
1.7 KiB
JavaScript
Raw Normal View History

2013-06-22 06:24:24 +00:00
'use strict';
define(
[
'signalR'
], function () {
_.extend(Backbone.Collection.prototype, {BindSignalR: function (options) {
if (!options) {
options = {};
}
if (!options.url) {
console.assert(this.url, 'url must be provided or collection must have url');
options['url'] = this.url.replace('api', 'signalr');
}
2013-05-05 21:24:33 +00:00
var self = this;
var _getStatus = function (status) {
switch (status) {
case 0:
return 'connecting';
case 1:
return 'connected';
case 2:
return 'reconnecting';
case 4:
return 'disconnected';
default:
throw 'invalid status ' + status;
}
};
2013-05-05 21:24:33 +00:00
var connection = $.connection(options.url);
2013-05-05 21:24:33 +00:00
connection.stateChanged(function (change) {
console.debug('{0} [{1}]'.format(options.url, _getStatus(change.newState)));
});
2013-05-05 21:24:33 +00:00
connection.received(function (message) {
console.debug(message);
if (options.onReceived) {
var context = options.context || self;
options.onReceived.call(context, message);
}
else {
self.fetch();
}
});
connection.start({ transport:
[
'longPolling'
] });
return this;
}});
});