Monday, March 28, 2011

extending jquery on the main element object

I've seen some jquery code where people extend the main object like:

 $('someId').myCustomObject();

Is this possible or am I mistaken? (if yes, how?)

From stackoverflow
  • I believe what you're looking for is jQuery.fn.extend:

    jQuery.fn.extend

  • Yes it's easily possible. The standard pattern for building extensions is:

    (function($) {
    
      $.fn.myCustomObject = function(options) {
        var defaults = { ... };
        var opts = $.extend(defaults, options);
    
        this.each(function(i) {
    
          ... // Act on each item, $(this).
          ... // Use opts.blah to read merged options.
    
        });
      };
    
    })(jQuery);
    

    This allows you to use '$' in the plug-in, yet allows compatibility mode.

    chipotle_warrior : That's the right pattern, except `this` is already a jQuery object, so you can call `this.each()` without wrapping it in the jQuery function.
    stusmith : Oopsies, my bad. I'll fix it. Cheers.

0 comments:

Post a Comment