How do I check if ydn.db database is ready for use?

386 views Asked by At

I can successfully create an indexeddb database and load data into it. I can also read data from this database from the same page. I then try and read from the database from another page on my site.

db = new ydn.db.Storage('test');
db.keys('items').done(function(d) {
    alert(d);
});

This does not work. I just get an empty result. However if I enter the above code into the javascript console of Chrome directly it does work. After looking around it seems that the database may not be ready. So I try this.

db = new ydn.db.Storage('test');
db.addEventListener('ready', function() {
    db.keys('items').done(function(d) {
        alert(d);
    });
});

This however gives me the the following error in the console.

Uncaught TypeError: undefined is not a function

The error is show for the following line of code.

db.addEventListener('ready', function() {

I am not sure what I am missing here.

1

There are 1 answers

0
Bud Damyanov On BEST ANSWER

Opening database connection is an asynchronous operation. This ready event listener is invoked when database is connected and after necessary schema changes are made. This is the first asynchronous function call make by the database instance.

If database opening fail, the callback is invoke with error event object. Multiple listener can be added. Heavy database write operation should invoke after this ready event handler. Alternatively ready event can be listen through DOM event listener pattern.

You can add database ready event listener in similar way:

var db = new ydn.db.Storage('test');
db.onReady(function(e) {
  if (e) {
    if (e.target.error) {
      console.log('Error due to: ' + e.target.error.name + ' ' + e.target.error.message);
    }
    throw e;
  }
  db.put('statement1', large_data);
});