Search code examples
javascripthtmlcachingmanifestydn-db

How to load a db context in another Html page using YDN-DB?


I've loaded all my data on the very first page:

<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> 
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/Scripts/ydn.db-jquery-0.7.5.js" type="text/javascript"></script>
<script src="/Scripts/jquery.mousewheel.js"></script>
...
var schema = {
        stores: [{
            name: 'products',
            keyPath: 'cdProduto',
            autoIncrement: false,
            indexes: [
                {
                    keyPath: 'cdCategoria'
                }, {
                    keyPath: 'dtUltimaAtualizacao'
                }]
        }]
    };

    var db = new ydn.db.Storage('db-test', schema);

    db.clear().done(function (num) {            
        db.add('products', [<%=jsonProducts%>]);            
    });

The <%=jsonProducts%> prints some json from C# back-end.

I can load the information like this, it works:

db.get('products', '2').always(function (record) {...

After, in the same browser and session, when I try to load my second page (/catalogo.html), then load the same product with the '2' key, like this:

<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> 
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script src="/Scripts/ydn.db-jquery-0.7.5.js" type="text/javascript"></script>
<script src="/Scripts/jquery.mousewheel.js"></script>
...
var db = new ydn.db.Storage('db-test');         
db.get('products', '2').done(function (value) {
    console.log(value);
});

It returns 'undefined' on the console. I have no clues.

Besides, im using html cache manifest on both pages

<html manifest="/home/manifest">

and testing under local server, acessing with localhost and port 60873, for example.

Am I missing something? Ain't that the right way to open an existing YDN-DB?

Thanks!


Solution

  • You are not missing anything and it should work. You should check indexeddb content on resource panel of dev console.

    You should initialize in second page /catalogo.html exactly as in first page, i.e,

    var db = new ydn.db.Storage('db-test', schema);
    

    Changing schema my drop some tables. Such data lost occur when database constraint are not met. It could be triggered by the library or browser itself.

    It is a good practice to check database connection before using as follow:

    db.addEventListener('ready', function (event) {
      var is_updated = event.getVersion() != event.getOldVersion();
      if (is_updated) {
        console.log('database connected with new schema');
      } else if (isNaN(event.getOldVersion()))  {
        console.log('new database created');
      } else {
        console.log('existing database connected');
      }
      // heavy database operations should start from this.
    });