Skip to content

Dexie.on.ready

David Fahlander edited this page Jul 30, 2014 · 11 revisions

Syntax

db.on("ready", function callback () {}, bSticky);

Parameters

callback: Function Callback to execute when database has successfully opened.
bSticky: Boolean Optional. If truthy, the subscriber will survive db.close();db.open();

Sample

db.on("ready", function() { alert ("Database ready"); });

Description

In case database is already open, the event will trigger immediately. If not open, it will trigger as soon as database becomes successfully opened. If subscribing to this event before or in the same tick as calling db.open(), your subscriber may return a Promise that will block the database until it is resolved or rejected. If the returned promise is rejected, the call to database open () will fail.

There are different use cases for this event.

Use Case 1: Execute code whenever database is open

This use case is similar to jQuery('document').ready() - if subscribing to the event before database is open, the subscriber will be queued and executed once database is ready, but if database is already open when subscribing to the event, the subscriber will be executed immediately. This use case is typically a one-shot subscription. In case database is closed and reopened, the subscriber will not be called again.

db.on("ready", function () {
    // Will trigger once and only once.
});

Use Case 2: Hook into the db.open() procedure and do additional db initialization

In case you want to initialize your database with contents before any operation executes, you may do so by subscribing to db.on('ready') within the same tick as you are calling db.open() and return a Promise. An example of this use case is when you want to initialize data from an ajax call.

Use Case 3: Extend Dexie

If you are building a plugin that will extend the open procedure, you may want to use the bSticky parameter to tell Dexie to let your subscriber not be a one-shot subscriber but survice calls to db.close() / db.open(). This is a rare use case for application code, since a database is typically opened only once in the application's life time.

db.on("ready", function () {
    // Will trigger each time db is successfully opened.
}, true);
Clone this wiki locally