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*/
}
});
});
-
2What exactly are you trying to accomplish?quantumSoup– quantumSoup2010年06月29日 12:49:24 +00:00Commented Jun 29, 2010 at 12:49
-
I'm trying a callback to work the right way, like in most jquery methods. $(document).ready(function(){*Evereything in here happens after Dom is loaded but not before, so it is a callback*/}); And I would like to know how to write a callback in my plugintylik– tylik2010年06月29日 16:12:15 +00:00Commented Jun 29, 2010 at 16:12
3 Answers 3
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.
Comments
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.
function loadAjax(paramUrl, paramData, paramType, paramAsync) {
var result = ""
$.ajax({
url: paramUrl,
data: paramData,
type: paramType,
async: paramAsync,
success: function (res) {
result = res
},
error: function (data) {
alert("Unexpected error: " + data.val());
}
});
return result;
}