jmans
jmans

Reputation: 5658

Setting JavaScript event handlers after the method call that would trigger the event?

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?

Upvotes: 2

Views: 290

Answers (3)

Andreas Köberle
Andreas Köberle

Reputation: 110922

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.

Upvotes: 2

jfriend00
jfriend00

Reputation: 707376

It appears that opening the database is just an open. It's not an actual DB request and the onsuccess handler is for an actual database request that comes later.

It is good practice to install event handlers before they could possibly be called, but in this case, the dbOpenRequest object doesn't exist until after the open call (it's returned as the result of the open call) so there is no way to put an onsuccess handler on it until after the open. Thus, the onsuccess handler has to be called some time later as a response to some event other than the open (probably a DB query) or never called at all.

Upvotes: 1

TimWolla
TimWolla

Reputation: 32701

It's probably because the open is asynchronous and it has some delay (Opening is not done instantly). JavaScript in the meantime proceeds executing (and binding the events).

Upvotes: 0

Related Questions