Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen authoring a jquery plugin, how do I call one of my main plugin methods from another method?
    text
    copied!<p>I'm following the guidelines for plugin authoring on jquery's website, but I'm having trouble figuring out how to call a main plugin method from another method within the same plugin.</p> <p>I have a plugin like this:</p> <pre><code>(function($){ var methods = { init: function(options) { var settings = {}; //this == context element of plugin, already jquery return this.each(function() { var $this = $(this); if( options ) { settings = $.extend({}, settings, options); } var data = $this.data('PluginData'); if(!data) { //set up } }); }, some_fn: function() { //do some stuff }, another_fn: function() { //do other stuff, then somehow call some_fn(), maybe via methods.some_fn() ? } }; jQuery.fn.SomePlugin = function(method) { if(methods[method]) { return methods[method].apply(this, Array.prototype.slice.call( arguments, 1)); } else if (typeof(method) == 'object' || !method) { return methods.init.apply(this, arguments); } else { console.log('there was an error'); } }; })(jQuery); </code></pre> <p>This is pretty much the skeleton code from jquery. However, what I'm having trouble with is figuring out the best way to create a "utility" function that is just for my plugin methods, or how to call one plugin method from another.</p> <p>For example, in my plugin, I have 3 methods, <code>init</code>, <code>some_fn</code>, and <code>another_fn</code>. When I call <code>$('#el').SomePlugin('another_fn')</code>, within <code>another_fn</code>, I'd like to call <code>some_fn</code>. How can I do this? Calling <code>methods.some_fn()</code> will probably work, however, then this is dependent on the order the methods are defined within the methods object, correct? So I could call <code>some_fn</code> from <code>another_fn</code>, but not vice versa?</p> <p>Additionally, what's the correct way to create a utility function that all the methods in my plugin can use, so that I am not cluttering the global namespace? Do I just define the utility functions at the beginning of my plugin, right before the call to var methods?</p> <p>EDIT: Thanks to Matt Ball, I have confirmed that methods.some_fn() DOES work for calling other main methods. Now I just want to know what the best practice for creating a (private) utility function is</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload