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: