0

Sorry if this is a base question but I seem to have a misconception on how plugins in JQuery work and Google ain't helping much.

Imagine I have:

methods = {
    init : function(opts){

        options = $.extend(options, opts);

        return this.each(function(){
            data = $(this).data('prodigal');

            if(!data){

                if(options.isActive === false){
                    $(options.tpl.overlay).css({ 'opacity': options.overlay.opacity }).appendTo('body');
                    options.isActive = true;
                }
            }
        });
    }
};

Now options.isActive is a boolean of true or false to say whether or not the options.tpl.overlay option should be added to the body of the document. It ensures my options.tpl.overlay appends only once to the document and it works, but I am unsure how it works.

When I call:

$('.view_title_images').prodigal();
$('.glglg').prodigal();

It still only adds once. I was always led to believe that the plugin is formed and the init function called for every "call" you make, i.e. $('.view_title_images,.glglg').prodigal(); would form and call the init function once.

So how exactly does the init function run in a JQuery plugin?

Sammaye
  • 43,242
  • 7
  • 104
  • 146

2 Answers2

0

Not sure that this is what is happening here but be aware that $(this) is not the same object whether being inside or outside a callback function.

Yannick Blondeau
  • 9,465
  • 8
  • 52
  • 74
  • Sorry yea I stand by my last comment I am not using `this` I am uisng `$(this)` – Sammaye Dec 05 '12 at 12:56
  • I still don't understand, in that article he says in his code snippets ` // now we are inside of a jQuery function, the DOM element is the context // so 'this' has changed to become a DOM element. ` which means that the way I can expect it to be what I ask for on my plugin – Sammaye Dec 05 '12 at 13:30
  • " which means that the way I can expect it to be what I ask for on my plugin" What I mean't was: I can expect `$(this)` to be what I expect it to be in my plugins `init` function – Sammaye Dec 05 '12 at 13:42
0

I am seeing this behaviour because the plugin is actually instantiated the first time it is run as a static object within the jQuery plugin framework.

So every successive call to the init function will call this global object. Since the options object is a reference to that object in the static object changing the boolean each time is actually saved for future calls to the plugin.

Sammaye
  • 43,242
  • 7
  • 104
  • 146