While looking into the IndexedDB API, I have found several examples of event handlers being set after the method call that looks like it should be triggering the event. For example:
var db = null;
try {
var dbOpenRequest = window.indexedDB.open("BookShop1");
dbOpenRequest.onsuccess = function(event){
db = dbOpenRequest.result;
DAO.version = db.version;
...
Although I’ve done quite a bit of development in JavaScript, I’m embarrassed to say that this looks strange to me. I feel like the event handlers ought to be set before the actual open() call, but I’ve seen this pattern in several examples. Could someone help me understand this?
Its cause of the single thread and asynchronous nature of JavaScript. When you call open the function is execute immediately. But the onsuccess callback will be put on the function stack of the single thread. These function can not called before the actual function is ended. So you can change the request object in the function and the callback is there when the onsuccess will called. This is nice article to understand the execution context stack.