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
You can’t, because if you try to namespace things in that way, you mess up the value of
thiswithin the method calls. (Specifically,thiswill refer to$.fn.myPluginrather than the actual jQuery object.)thisin 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 onthis: Mythical Methods.)The primary way
thisgets set is when you call a function that’s a property on an object:That tells JavaScript to look up the property
baron thefooobject and try to call it, settingthis = foowithin the call. So you can see why if you do$("selector").myPlugin.plugin_1(),thisends up referencingmyPlugin, 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).