I am creating a plugin and it cannot access $(this). A simple overview of my plugin is
(function($){
$.fn.myPlugin= function(options, callback) {
return this.each(function(){
$(this).click(function(){
// some plugin works ..
callback();
});
});
};
})(jQuery);
Then i attached my plugin to a element like
$('p').myPlugin({
// Some options
}, function(){
alert('first test');
alert($(this).text());
});
Here when the element p is clicked, i get the first alert, but i didn’t get the 2nd alert.
The callback function is called, but unable to access this.
Is there any problem with the defining or with code ? any alternative suggestion will also be helpful
Instead of
callback();, use.apply()to give it the right context (otherwise it’swindow), like this:You can see the updated/working version here.
For a more complete overview here, you can pass more arguments if you want to that
callback, for example if you wanted to make theoptionsavailable, you could do this:Then call it like this:
You can give that one a try here, just add whatever arguments you want to that array,
callback()will be called with those arguments 🙂