I'm still trying to get oriented with JS, and have recently had a lot of trouble understanding the role of callbacks.
I can see that callbacks offer a more asynchronous(?) way of returning values generated in a function. For example, this makes sense to me:
function summation (a, b, _callback) {
if (typeof(_callback) === 'function') {
_callback(a+b);
}
}
$(document).ready(function () {
summation(2,3,function (_val) {
console.log(_val);
}
});
As opposed to something like var _val = summation(2,3); Where var isn't available immediately following the assignment.
I have difficulty making this process scale as I attempt to manipulate elements on a webpage with jQuery. I have an object which tracks elements:
function createObj (_callback) {
var test = new Object();
test.mainPane = $('#mainPane');
if (typeof(_callback) === 'function') {
_callback(test);
}
}
If I wish to pass test.mainPane into a function fitToPage() which adjusts the properties of the element to fit a given screen size, and then want to pass the element to another function createElems() which adds children to the element, things begin to fall apart:
$(document).ready(function () {
createObj(function (test) {
fitToPage(test, function (test) {
createElems(test, null);
});
});
});
And it only seems to get worse if I try avoiding this callback hell(?) by creating special functions which do nothing but help me manage the callbacks to other functions. I'm confident that I've missed something important, but haven't come up with the correct search terms to find it. Is there a better method?
function summation(a,b) { return a + b; }?