Jordon Bedwell
Jordon Bedwell

Reputation: 3247

Multiple jQuery plugins from a single object

How would one go about creating multiple plugins for jQuery from a single object?

Initially I tried:

(function($) {
  $.fn.myPlugin = {
    plugin_1: function(options) { alert(this.text( )); },
    plugin_2: function(options) { alert(this.text( )); }
  }
})(jQuery);

However, upon doing $('#element').myPlugin.plugin_1( ); I got: this.text is not a function

Upvotes: 1

Views: 94

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

You can't, because if you try to namespace things in that way, you mess up the value of this within the method calls. (Specifically, this will refer to $.fn.myPlugin rather than the actual jQuery object.)

this in JavaScript is quite different than it is in other languages you may be familiar with, such as C++, Java, or C#. It's defined entirely by how the function is called, not where the function is defined. (More on this: Mythical Methods.)

The primary way this gets set is when you call a function that's a property on an object:

foo.bar();

That tells JavaScript to look up the property bar on the foo object and try to call it, setting this = foo within the call. So you can see why if you do $("selector").myPlugin.plugin_1(), this ends up referencing myPlugin, not the jQuery object.

You'll have to use a naming convention instead, such as $.fn.myPlugin_plugin1, or just keep them separate, but with similar-enough names that people know they're grouped ($.fn.myPluginFoo, $.fn.myPluginBar).

Upvotes: 2

Related Questions