1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

jQuery.fn.extend

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.