tags:

views:

54

answers:

2

I have a problem in creating a callback function. First, as far as I can understand, a callback acts like a parametr which triggers when all the action in its "parent" function has finished. For example:

$('p').hide('slow', function() {
    $(this).show('slow');
});

At first <p> is hidden, and only afterwards it shows again.

How can I apply such callback in a random plugin?

For example a plugin looks like this:

 $.fn.myPlugin = function(settings) { 
   return this.each(function() {
    settings = $.extend({ onShow: null }, settings);
    $(this).hide('slow');  /*This action should happen first (First action)*/
    if ( $.isFunction( settings.onShow ) ) 
     settings.onShow.call(this);/*Callback should fire after First action has stopped*/
     }
   });
 };


$(document).ready(function() 
   $('p').myPlugin({
     onShow: function() {
     alert('My callback!');/*Both actions(element hiding and alert ) 
                             fire simultaneously, but I need alert 
                             to fire after element is hidden*/
      }
   });
});
+4  A: 

You can't apply it in a random plugin. If the plugin is not written to trigger callback functions when different events occur you cannot use them.

Darin Dimitrov
+1  A: 

A callback function is a function, which is passed to another function/method and gets called at some point.

If we create a function like

function mightyplugin(foo, callback){
   // big code block here

   callback.apply(this, [foo]);
}

we now have a function, which calls another function. In this example, it parses one parameter through it and calls our callback-function within the scope of this.

A call would look like

mightyplugin("Bar!", function(param){
    alert(param);
});

we pass an anonymous function (more precisly, a reference) to mightyplugin() and we can access our parameter in there, since we call that anonymous function with a scope and an array of parameters (which only holds the original parameter here).

Those constructs must already be implemented by a plugin, otherwise you need to create your own functionality.

jAndy
Thanks for your answer. But I need a callback to be triggered only after mightyPlugin has finished doing everything else assigned to it
tylik
// big code block here sholud happen first, and only after that a callback should fire
tylik