Skip to content

Instantly share code, notes, and snippets.

@tanema
Created August 21, 2012 14:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tanema/3415831 to your computer and use it in GitHub Desktop.
Save tanema/3415831 to your computer and use it in GitHub Desktop.
cookie listener for changes
function cookieListener(cookieName, callback) {
this.cookiename = cookieName;
this.callback = callback;
this.cookieRegistry = [];
this.interval = setInterval(this.observe, 100);
}
cookieListener.prototype.CREATED = 'created';
cookieListener.prototype.DELETED = 'deleted';
cookieListener.prototype.UPDATED = 'updated';
cookieListener.prototype.observe = function() {
var cookieVal = $.cookie(cookieName),
status = null;
if (this.cookieRegistry[this.cookieName] == null && cookieVal != null) {
status = cookieListener.prototype.CREATED
}else if(this.cookieRegistry[cookieName] != null && cookieVal == null){
status = cookieListener.prototype.DELETED
}else if(cookieVal != this.cookieRegistry[cookieName]){
status = cookieListener.prototype.UPDATED
}
this.cookieRegistry[this.cookieName] = cookieVal;
if(status)this.callback(status);
return status;
}
cookieListener.prototype.removeListener = function(){
clearInterval(this.interval)
}
// bind the listener
var cl = new cookieListener('foo', function(status) {
if(status == cookieListener.prototype.DELETED = 'deleted')
alert('oh no')!
});
@djlaidler
Copy link

Did you ever find a solution that doesn't involve setInterval?
This has issues for two reasons;

  1. It's endless, and creates unnecessary computations and load
  2. It will average a 50ms lag, which given most will need to act swiftly on the response, maybe prohibitive to use

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment