I am trying to write a function with multiple callback functions. Am I doing this right or is there a better way?
$('.question a').click(function(ev) {
$('.answers').load(url, function() {
$('#AnswerBox').addClass('mceEditor',
function() {tinyMCE.init({
theme : "advanced",
mode : "specific_textareas",
editor_selector : "AnswerBox",
elements: "AnswerBox",
plugins : "fullpage",
theme_advanced_buttons3_add : "fullpage",
});
})
})
return false;
});
I know you can do a 2-layer function in this way, but can you also do more?
-
1You can add any function at any place a callback is expected. However, I don't find a method addClass in jQuery that allow to set a CSS class and give a callback. Take a look at : api.jquery.com/addClassMatRt– MatRt2013年01月15日 03:21:33 +00:00Commented Jan 15, 2013 at 3:21
3 Answers 3
Yes, you can nest more functions, but callback functions are used to know when asynchronous events are complete.Setting class doesn't happen asynchronously, so you dont have any callback function in addClass. So it should be something like,
$('.question a').click(function(ev) {
$('.answers').load(url, function() {
$('#AnswerBox').addClass('mceEditor').
tinyMCE({
theme : "advanced",
mode : "specific_textareas",
editor_selector : "AnswerBox",
elements: "AnswerBox",
plugins : "fullpage",
theme_advanced_buttons3_add : "fullpage"
});
});
return false;
});
Comments
You can nest more than "3 layers deep." Though, you're using the jQuery.addClass method incorrectly.
See http://api.jquery.com/addClass/
That's, most likely, where your issue is.
Comments
Any function scope can contain other function definitions which can then contain more defintions and so on as deep as you want to go.
When you do that, those function definitions are local only to within that function scope. Since any function scope can contain other function definitions, it can go as deep as you want to go, probably limited only by some internal memory or stack limitations in a given javascript limitation. Practically speaking, you are not likely to hit a limit unless you intentionally make some devious structure that has no practical purpose.