tags:

views:

124

answers:

2

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?)

A: 

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

jQuery.fn.extend

Rich
+3  A: 

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.

stusmith
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.
chipotle_warrior
Oopsies, my bad. I'll fix it. Cheers.
stusmith