Writing jQuery functions that allow chaining
I want to write some开发者_如何学运维 code that allows me to replace jQuery's animate function with one that does different things, but still allows me to call a secondary function on completion.
At the moment, I'm writing lots of code like this;
if (cssTransitions) {
$("#content_box").css("height",0);
window.setTimeout(function() {
secondFunction();
}, 600);
} else {
$("#content_box").animate({
height:0
}, 600, function() {
secondFunction();
});
}
I'd much rather write a function that looks like this:
function slideUpContent(object) {
if (cssTransitions) {
object.css("height",0);
// Not sure how I get a callback here
} else {
$("#content_box").animate({
height:0
}, 600, function() {
});
}
}
That I could use like this:
slideUpContent("#content_box", function(){
secondFunction();
});
But I'm not sure how to get the functionality I need - namely a way to run another function once my one has completed.
Can anyone help my rather addled brain?
The functionality you are looking for is called a callback.
It is simple enough to implement. Just pass the anonymous function (or other function) as a parameter, then call the variable passed in by appending brackets callback()
(obviously checking to see if it is a valid function first).
function slideUpContent(object, callback) {
if (cssTransitions) {
object.css("height",0);
// Perform callback if set
if ($.isFunction(callback)) {
callback();
}
} else {
$("#content_box").animate({
height:0
}, 600, callback);
}
}
Chaining usually means returning this so you can do
$("selector").function1().function2();
For your example, you just need
function1(param1, f) {
// do stuff
f();
}
then call it with
function1("parameter", function2);
I had recently created a sequence opening animation for a website. I found this website to be a good source of information. The part that might be helpful for you is the section titled, "Creating a sequence of animations".
http://www.elated.com/articles/super-easy-animated-effects-with-jquery/
精彩评论