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

jquery.delayedObserver 0.5

h3  ~  24 Feb 2008, 21:13  –  post a comment

Reading the release notes of jQuerie 1.2.3 I learned that the data method now supported namespaces, and the existence of this method altogether (since 1.2.2 ?!). This handful method can store information on DOM element gracefully, so I don't need to use a stack and closures, rejoice.

/*
 jQuery delayed observer - 0.5
 http://code.google.com/p/jquery-utils/

 (c) Maxime Haineault <haineault@gmail.com>
 http://haineault.com
 
 MIT License (http://www.opensource.org/licenses/mit-license.php)
 
 Changelog
 =========
 0.2 using closure, special thanks to Stephen Goguen & Tane Piper.
 0.3 now allow object chaining, added license
 0.4 code cleanup, added support for other events than keyup, fixed variable scope
 0.5 changed filename, included in jquery-utils 
     complete rewrite, same structure but more compact, 
     now using jquery's "data" method instead of a stack to store data
     it's now possible to change the condition, by default it's "if new this.val == this.oldval"
     now using this.each to support multiple observed elements
*/

(function($){
  $.extend($.fn, {
    delayedObserver: function(callback, delay, options){
      this.each(function(){
          var $obj    = $(this);
          var options = options || {};
          $obj.data('oldval',  $obj.val())
            .data('delay',     delay || 0.5)
            .data('condition', options.condition || function() {
              return ($(this).data('oldval') == $(this).val());
            })
            .data('callback',  callback)
            [(options.event||'keyup')](function(){
              if ($obj.data('condition').apply($obj)) return;
              else {
                if ($obj.data('timer')) clearTimeout($obj.data('timer'));

                  $obj.data('timer', setTimeout(function(){
                    $obj.data('callback').apply($obj);
                  }, $obj.data('delay') * 1000));

                  $obj.data('oldval', $obj.val());
              }
            });
          });
    }
  });
})(jQuery);

Usage example:

$(document).ready(function(){
    $('#ajax-search').delayedObserver(function(){
        $('body').append($('<div>callback function called!</div>'));
    }, 0.5);
}); 

Plain text source code (trunk)

I'd consider this somewhere between alpha and beta, so be warned :p Of course don't hesitate to give me suggestions or ideas if you like this script.

*argh*, writing this I just noticed that I forgot this.each to .. fixed.

post a comment Comments

no comments :|

Copyrighted stuff .. u know.