Reputation: 619
i have tried a website which dynamically generates the plugin for you. Here's the site http://starter.pixelgraphics.us/
Here's a sample of the generated code.
(function($){
$.sample = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("sample", base);
base.init = function(){
base.options = $.extend({},$.sample.defaultOptions, options);
// Put your initialization code here
};
// Sample Function, Uncomment to use
// base.functionName = function(paramaters){
//
// };
// Run initializer
base.init();
};
$.sample.defaultOptions = {
};
$.fn.sample = function(options){
return this.each(function(){
(new $.sample(this, options));
});
};
})(jQuery);
The part that i'm confused about is the code inside $.fn.sample.
Does the code loops over a jQuery collection then attach the Object created using $.sample into each DOM object which is part of the jQuery collection? If that's the case is there any issues when using this approach.
Btw, i would like to ask for instances wherein there could be an issue with the scope of the "THIS" object. Because i'm a little confused with the comment preceding the assignment of the "THIS" object to the variable "base".
thanks in advance.
I've realized that this plugin creates global Objects. For example, i have 100 div then i call this plugin $(div).sample(). It creates 100 Global Objects having attributes such as Obj.el and Obj.$el corresponding to the DOM and jQuery version of the DOM respectively. Is it just okay to use this approach in creating plugins?
Upvotes: -1
Views: 403
Reputation: 822
a) the code you posted only declares the plugin. It will be attached to dom with something like
$('.my-selector').sample();
With this code, jquery will iterate over all elements with .my-selector class and execute the sample() plugin for each one
b) You are suggested to use "base" instead of "this" so to avoid confusion and common errors in the code. Maybe it's already obvious but "this" change values depending on scope of code executed. "base" is a closure over the starting scope of the plugin. http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this
Upvotes: 2
Reputation: 13775
What the code is doing is creating the sample plugin on each dom object you're attaching it to. So, if you used $('inputs')
and you have 5 inputs, you would create the plugin on each one, using the options you passed in.
Upvotes: 1