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*/
}
});
});
A
callback functionis a function, which is passed to another function/method and gets called at some point.If we create a function like
we now have a function, which calls another function. In this example, it parses
oneparameter through it and calls our callback-function within the scope ofthis.A call would look like
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.