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's window), like this:
callback.apply(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 the options available, you could do this:
(function($){
$.fn.myPlugin= function(options, callback) {
return this.each(function(){
$(this).click(function(){
callback.apply(this, [options]);
});
});
};
})(jQuery);
Then call it like this:
$('p').myPlugin({
thing: "thing1"
}, function(opts){
alert(opts.thing); //thing1
});
You can give that one a try here, just add whatever arguments you want to that array, callback() will be called with those arguments :)
Nick Craver is right. But for understanding what is going on follow this link: http://howtonode.org/what-is-this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With