M.M M.M - 3 months ago 22
Javascript Question

jQuery plugin return this.each

I am bulding a plugin let's call it

ptest
and I want to be able to call it with:

$(".myClassName").ptest();


Since I am using attributes from the element on which the plugin is called, lets say
data-attribute
I now know that returning
this.each(...);
is a must.

Here is my code:

(function($){
var op;
$.fn.ptest = function(options) {
op = $.extend({
target: null,
attribute: null
}, options);

return this.each(function(){
op.target = $(this);
op.attribute = op.target.attr("data-attribute");
bind();
});
};
function bind(){
op.target.find('.clickable').bind('click',log);
}
function log(){
console.log(op.attribute);
}
}(jQuery));


I know that by having
op
as a global variable it will always retain the last value for the
attribute
and the
target
. How can I make the op variable retain the correct value for each element of
.myClassName
while being able to access each
op
from
log
or
bind
functions?

I sense i need to declare the functions and the variable in a different way, but how?




I have looked at a lot of different questions and tutorials, here are some:


Answer

If bind and log really need access to the specific element in the loop, then you need to define them within the each callback, and make op local to that callback:

(function($){
    $.fn.ptest = function(options) {

        return this.each(function(){
            var op = $.extend({
                target: $(this)
            }, options);
            op.attribute = op.target.attr("data-attribute");
            bind();

            function bind(){
                op.target.find('.clickable').bind('click',log);
            }
            function log(){
                console.log(op.attribute);
            }
        });
    };
}(jQuery));

But depending on how you're using bind and log, there may be other options available.