user3629892
user3629892

Reputation: 3046

Understanding event handling and callbacks in JavaScript

I was messing around with IndexedDB and I realised that I don't really get event handling in JavaScript.

So here's the code:

var request = indexeddb.open(bla, version);

request.onsuccess = function (event) {  };

So the open-method returns a IDBOpenDBRequest object, which, according to Mozillas site, inherits from IDBRequest, which apart from properties and methods also has event handlers, one of them being onsuccess:

https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.onsuccess

So on the Mozilla site, onsuccess is just function () { }

Now, when the database was opened successfully, the onsuccess event fires and the appropriate event handler is called, in this case the function that I defined, but how exactly does that happen?

The request variable contains an instance of the IDBOpenDBRequest. So when I write request.onsuccess = somefunction(), am I overwriting the default function of the IDBRequest class?

I don't get why I can write request.onsuccess = somefunction(event) { } and how the event is passed to that function.

EDIT:

function myObect() {
    this.open = function(a,b,c) {
        if (c > 20) {
            this.success("String");
        }
    };
};


var myrequest = new myObect();
myrequest.open(4,2,21);
myrequest.success = function (ev) {
    console.log(ev);
};

Upvotes: 0

Views: 152

Answers (2)

fgb
fgb

Reputation: 18559

To create a similar api, you can do something like:

function open(a, b, c) {
    var request = {};

    if(c > 20) {
        setTimeout(function() {
            if(typeof request.success === "function") {
                request.success("String");
            }
        }, 1);
    }

    return request;
}

var myrequest = open(4, 2, 21);
myrequest.success = function(ev) {
    console.log(ev);
};

Here, setTimeout is asynchronous so the callback function is not executed immediately. When any asynchronous task is run in JavaScript, the currently executing code will run to completion before any callback is called. So success is guaranteed to be set before request.success called.

The Indexed DB open call similarly runs an asynchronous task, and then dispatches events when it is finished which will eventually call your callback function.

Upvotes: 3

Zav
Zav

Reputation: 661

I overwriting the default function of the IDBRequest-class

Looks like there is no default behavior, so you just set up your own func.

Upvotes: 0

Related Questions