jquery chaining generic callback function
Often times I come across situations where I want to execute a jQuery function or initialize a jQuery plugin like jQuery datatables and would like to have code execute after the function has finished. jQuery functions such as hide or fadein or other transformation functions take an optional callback parameter to accomplish this. However there are other jQuery functions which just return the 'this' object to allow for chaining. I would like to know if there is a way using chaining or s开发者_运维技巧ome other method to execute some kind of generic function which takes a callback after whatever jQuery function I call finishes.
Something like:
$("#element").datatable().executeCallback(myCallbackFunction);
You just need a plugin which takes a function argument, applies it to everything matched by the object, and returns the object itself. A simple chainable "genericCallback" implementation:
function makeRed() {
$(this).css("border", "1px solid red");
}
$.fn.genericCallback = function(fn) {
if(!typeof fn === 'function') {
console.log('Function expected, got a ' + typeof fn);
}
return this.each(function() {
fn.apply(this);
});
};
$("div").genericCallback(makeRed);
You can try it here.
Take a look at jquery queue http://api.jquery.com/queue/, this might help you.
This isn't very robust but it does what you want for generic callbacks.
$.fn.executeCallback = function( fn )
{
window[fn]();
}
精彩评论