Notice This is a beta feature offered by Google. Also this is automatic translation, which means the results are often inacurate and/or hilarious. Enjoy.

ARCHIVES / RSS
Blog

Delayed observer for jQuery fixed (using real closures)

h3  ~  23 Sep 2007, 13:30  –  post a comment

Soon after my last post about my jQuery delayed observer I got feedback from two readers who pointed me out that I could achieve closures by wrapping my code in a anonymous function like this;

(function() {
  /* code visible only to the observer */
  jQuery.fn.extend({
    /* code visible in the jQuery namespace */
  });
})();

I'd like to thanks Stephen Goguen and Tane Piper who gave me roughly the same code example that enlighten me on jQuery's closures.

Sorry if it took a while to post it, I was quite busy and sick at the same time. Short story, my last week was awful.

So here's the closure fixed version:

/*
 jQuery delayed observer
 (c) 2007 - Maxime Haineault (max@centdessin.com)
 
 Special thanks to Stephen Goguen & Tane Piper.
*/

(function() {
  var delayedObserverStack = [];
  var observed;
 
  function delayedObserverCallback(stackPos) {
    observed = delayedObserverStack[stackPos];
    if (observed.timer) clearTimeout(observed.timer);
   
    observed.timer = setTimeout(function(){
      observed.timer = null;
      observed.callback(observed.obj.val(), observed.obj);
    }, observed.delay * 1000);

    observed.oldVal = observed.obj.val();
  } 
 
  jQuery.fn.extend({
    delayedObserver:function(delay, callback){
      $this = $(this);
     
      delayedObserverStack.push({
        obj: $this, timer: null, delay: delay,
        oldVal: $this.val(), callback: callback
      });
       
      stackPos = delayedObserverStack.length-1;
     
      $this.keyup(function() {
        observed = delayedObserverStack[stackPos];
          if (observed.obj.val() == observed.obj.oldVal) return;
          else delayedObserverCallback(stackPos);
      });
    }
  });
})();

post a comment Comments

no comments :|

Copyrighted stuff .. u know.