My first jQuery plugin, where do functions and global variables go?

I am writing my first jQuery plugin, and I have a few questions about where I should put things. I tried searching, but it seems that there are different ways to structure plugins, so I got lost. I got this far by following the Authoring Plugins docs on jQuerys, but was not sure where to go next.

  • Where do I use a generic function? Take hi () for example. Let's say I plan to use this feature throughout the plugin, where should it live? Right now I put it upstairs, which seems to work, but I'm not sure if this is correct.

  • Where can I put a global variable? Take, for example, my "imgs" array. Should I declare this when I have it now, or in the init method or somewhere else?

    (function($){ function hello(){ alert("hello world"); } var imgs = new Array(); var methods = { init: function(options){ if(options){ $.extend({ width: 200, height: 200, selectedColor: '#123456' }, options); // for every image do something this.find('img').each(function(){ var $this = $(this); var width = $this.width(); var height = $this.height(); console.log("width: " + width + " height: " + height); selection = function() { console.log($this.attr('src')); hello(); }; $this.bind('click', selection); }); } return this; }, test : function( string ) { console.log("Test: " + string); //return "here"; } }; $.fn.Thumbnails = function(method) { // Method calling logic 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 { $.error( 'Method ' + method + ' does not exist on jQuery.Thumbnails' ); } }; })(jQuery); $thumbnails = $('#imagescontainer').Thumbnails({ height: 150, }); 

Thanks for the help!

+7
source share
1 answer
  • Put them outside the jQuery function, but inside the self-emitting function. This ensures that they exist only for your jQuery function. For example, you can see that the findText() utility function is outside the jQuery function in my bumpyText plugin.

  • It depends on its required service life. If you need it for calling your function, put it inside your function. If it needs to maintain its state for each plugin prompt (unlikely), put it outside the jQuery function.

+7
source

All Articles