0

I have added callback to my jQuery plugin.

$.fn.myPlg= function(options, callback) {
    if(callback) {
       //do stuff
    }
}

How now call this callback from jQuery e.g

$(document).myPlg( function(){

// how to call callback?

});
2
  • 3
    You don't call the callback from the second block of code, you call the callback from the first. The second block IS the callback. Commented Oct 24, 2011 at 12:57
  • @BNL - sorry, can you explain please. I don't fully understand that. I want to execute the code after plugin is done working. Is the callback the correct way of doing this? Any example, please? Commented Oct 24, 2011 at 13:29

2 Answers 2

1

This will cause the callback function to execute:

$.fn.myPlg= function(options, callback) {
    if(callback) {
       callback();
    }
}

As Samich said, you should use an options object, even if the callback is your only option. That way you can add more options easily.

doing it that way would look like this:

$.fn.myPlg= function(options) {
    if(options.callback) {
       options.callback();
    }
}

and

$(document).myPlg({
   callback: function() { 
     // callback logic here
   } 
});
Sign up to request clarification or add additional context in comments.

2 Comments

So callback(); from my plugin will execute the callback: function() { // callback logic here } form here?
OK. I understand much more now. Thanks for you time and effort.
0

In your case it will be second parameter:

$(document).myPlg({option1: 'a', option2: 'b'}, function(){
   // callback logic here
});

But please note that you need to call callback inside of plugin definition, not usage. I mean in the first part of your samples.

It's better to include it in options:

$.fn.myPlg= function(options) {
    if(options.callback) {
       //do stuff
    }
}

$(document).myPlg({
   option1: 'a', 
   option2: 'b', 
   callback: function() { 
         // callback logic here
   } 
});

6 Comments

How about the case where there are no more option than callback?
Then your plugin should be able to handle first parameter as callback.
Do I have to use callback in myPlg selector to run the code in the plugin? if(options.callback) { //here }
Actually callback should be called inside of the plugin and you are putting it as a parameter. So, when you initializing your plugin you just defining the callback, not calling it.
In the first sample of the answer I only defines the callback and in the plugin aonly initialization code invokes. You can call callback but I don't think that it will be good solution.
|

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.