Hey there! Long time no see. ^^
I'd brought a simple snippet with me. Hopefully this'll help you on understanding callbacks.
So, if you'd have a function and you'd want it to be like something that jQuery have:
- Code:
[panda=js]$(document).ready(function() {
// code here...
});
It's pretty simple. Here's my way to implement something like that.
- Code:
[panda=js]function hitsuCallback(action,callback) { // create a new function
eval(action); // I know it's ev(i)l, but this is just an example code so what
if(callback && typeof callback == "function") { // check if callback exists and then check the type of callback
callback(); // do the callback
}else{ // else if the callback doesn't exist and the callback wasn't a function
// do nothing
}
}
So this is how we'd use it:
- Code:
[panda=js]hitsuCallback("console.log('Hello world')", function() {
alert("Hey there");
});
It'll log 'Hello world' into console and alert 'Hey there'.
And what if the callback isn't called?
Let's assume that we'd use the code like this.
- Code:
hitsuCallback("console.log('Hello world')");
It might work as well, it'll log the message in the console with no problem.
That's everything I want to explain. Hope you understand!