3

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

3 Answers 3

4

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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Can you please post a complete example that uses the autocomplete widget?

Here is what I wanted to do...

    $('.suggest').autocomplete({
    source: function(request, response) {
        typ = $(this).getAttr("class").split(" ")[2]
        ....

...but this returns undefined. For now I am using document.activeElement, but I would prefer Nick Craver's method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.