views:

38

answers:

2

Hello,

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

+4  A: 

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
+1  A: 

Nick Craver is right. But for understanding what is going on follow this link: http://howtonode.org/what-is-this

Skay