2. O Ciclo de Eventos JavaScript
function maybe() {
console.log("…execute async, maybe?");
}
function proveIt() {
setTimeout(maybe, 0);
console.log("Hey, you just invoked me, and this is crazy…");
console.log("But I'll queue you up");
return "and you'll…";
}
proveIt();
3. Callbacks
function saveStuff(stuff, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://dev.jquery.com/~john/xdomain/test.php", true);
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
cb(null, xhr.responseText);
} else {
cb(error);
}
}
};
xhr.onerror = function (err) {
cb(err);
}
xhr.send(null);
}
saveStuff(stuff, function (err, data) {
if (err !== null) {
return err;
}
return data;
});
5. Callback Binding
var allTheCustomerThings;
$("#getCustomer").click(function (cust) {
var id = $("#cust-id").val();
getCustomer(id, function (cust) {
allTheCustomerThings = cust;
getContacts(id, function (contacts) {
allTheCustomerThings.contacts = contacts;
getOrders(id, function (orders) {
allTheCustomerThings.orders = orders;
getAccountsRecv(id, function (ar) {
allTheCustomerThings.ar = ar;
// OK - we got all the data, NOW WHAT?! :-)
});
});
});
});
});