diff --git a/README.md b/README.md index d14954c..bcb5e35 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,22 @@ Now, when we publish to a channel, we can pass the `:except` option, with the cu Now, the original client won't get the duplicated chat message, even if it's subscribed to the __/chat__ channel. +##Singleton subscription + +Sometime you need to have only one subscription to a channel, regardless the number of times you call `subscribe`. It may be useful when you subscribe in an AJAX callback. To do so, you can use `singleSubscribe`. + +jQuery('.user a.follow').live('click', function(event){ + jQuery.post(this.href, function(data, status, xhr){ + var channel = "users/" + data.user.id + "/feed"; + juggernaut.singleSubscribe(channel, function(feedEntry){ + console.log("Got new feed entry: " + feedEntry); + } + }); +}); + +Even if the user click many times to follow an user, each new messages of this users's feed will be pushed to the client only once. + + ##Server Events When a client connects & disconnects, Juggernaut triggers a callback. You can listen to these callbacks from the Ruby client, diff --git a/client/vendor/assets/javascripts/juggernaut.js b/client/vendor/assets/javascripts/juggernaut.js index 5462fe1..edf45d9 100644 --- a/client/vendor/assets/javascripts/juggernaut.js +++ b/client/vendor/assets/javascripts/juggernaut.js @@ -6,8 +6,9 @@ var Juggernaut = function(options){ this.options.host = this.options.host || window.location.hostname; this.options.port = this.options.port || 8080; - this.handlers = {}; - this.meta = this.options.meta; + this.subscriptions = {}; + this.handlers = {}; + this.meta = this.options.meta; this.io = io.connect(this.options.host, this.options); @@ -67,9 +68,20 @@ Juggernaut.fn.subscribe = function(channel, callback){ } }; +Juggernaut.fn.singleSubscribe = function(channel, callback){ + if ( this.subscriptions[channel] ) return false; + else { + this.subscribe(channel, callback); + return(this.subscriptions[channel] = true); + } +}; + Juggernaut.fn.unsubscribe = function(channel) { if ( !channel ) throw "Must provide a channel"; + if ( this.subscriptions[channel] ) + this.subscriptions[channel] = false; + this.unbind(channel + ":data"); var message = new Juggernaut.Message;