Skip to content

Instantly share code, notes, and snippets.

@paton
Created February 22, 2014 22:09
Show Gist options
  • Save paton/9163190 to your computer and use it in GitHub Desktop.
Save paton/9163190 to your computer and use it in GitHub Desktop.
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var log = require('../libs/logging');
var pubnub = require('pubnub');
require('cookie');
function Socket() {
_.extend(this, Backbone.Events);
};
Socket.prototype = {
binds: {},
initialize: function() {
var _this = this;
var userToken = (window.Auth.me() && window.Auth.me().get('user_id')) || Math.floor(Math.random()*10000000);
var channelBuffer = [];
_.each(_.keys(this.binds), function(channel) {
_this.sockUnbind(channel);
channelBuffer.push(channel);
});
this.pub = pubnub.init({
subscribe_key: Globals.pubnub.subscribe_key,
ssl: window.location.protocol === 'https:' ? true : false,
origin: 'pubsub.pubnub.com',
uuid: userToken,
noleave: true,
});
alert(1)
_.each(channelBuffer, function(channel) {
_this.sockBind(channel);
});
},
send: function(channel, subChannel, data) {
this.pub.publish({
channel: channel,
message: {
__type__: subChannel,
__packet__: data
}
});
},
// Bind without a presence listener
sockBind: function(bindChannel) {
var _this = this;
if(!bindChannel) {
return;
}
this.pub.subscribe({
channel: bindChannel,
message: function(msg) {
_this.trigger('message', msg);
}
});
this.updateBindCount(bindChannel);
},
// Bind WITH a presence listener
presenceBind: function(bindChannel) {
var _this = this;
if(!bindChannel) {
return;
}
this.pub.subscribe({
channel: bindChannel,
message: function(msg) {
_this.trigger('message', msg);
},
presence: function(data) {
_this.trigger('message', {
__type__: bindChannel + ':channelUpdated',
__packet__: data
});
}
});
this.updateBindCount(bindChannel);
},
silentBind: function(bindChannel) {
var _this = this;
if(!bindChannel) {
return;
}
this.pub.subscribe({
channel: bindChannel,
message: function(){}
});
this.updateBindCount(bindChannel);
},
updateBindCount: function(bindChannel) {
if(!this.binds[bindChannel]) {
this.binds[bindChannel] = 1;
} else {
this.binds[bindChannel] += 1;
}
},
sockUnbind: function(bindChannel) {
var _this = this;
if(this.binds[bindChannel] && (--this.binds[bindChannel]) == 0) {
delete this.binds[bindChannel];
_.defer(function() {
_this.pub.unsubscribe({
channel: bindChannel
});
});
}
},
};
module.exports = Socket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment