码迷,mamicode.com
首页 > 其他好文 > 详细

[PWA] 14. Loop cursor

时间:2016-05-18 06:51:15      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

import idb from ‘idb‘;

var dbPromise = idb.open(‘test-db‘, 4, function (upgradeDb) {
    switch (upgradeDb.oldVersion) {
        case 0:
            // keyval store is already created at version 1
            var keyValStore = upgradeDb.createObjectStore(‘keyval‘);
            keyValStore.put("world", "hello");
        case 1:
            // new version
            upgradeDb.createObjectStore(‘people‘, {keyPath: ‘name‘});
        case 2:
            var peopleStore = upgradeDb.transaction.objectStore(‘people‘);
            peopleStore.createIndex(‘animal‘, ‘favoriteAnimal‘);
        case 3:
            var peopleStore = upgradeDb.transaction.objectStore(‘people‘);
            peopleStore.createIndex(‘age‘, ‘age‘);
    }
});

// read "hello" in "keyval"
dbPromise.then(function (db) {
    var tx = db.transaction(‘keyval‘); // Open a transaction
    var keyValStore = tx.objectStore(‘keyval‘); // read the store
    return keyValStore.get(‘hello‘); // get value by key
}).then(function (val) {
    console.log(‘The value of "hello" is:‘, val);
});


dbPromise.then(function (db) {
    var tx = db.transaction(‘people‘, ‘readwrite‘);
    var peopleStore = tx.objectStore(‘people‘);

    peopleStore.put({
        name: "John", // name is the key
        age: 23,
        favoriteAnimal: ‘cat‘
    });
    peopleStore.put({
        name: "Joe", // name is the key
        age: 21,
        favoriteAnimal: ‘cat‘
    });
    peopleStore.put({
        name: "Jie", // name is the key
        age: 22,
        favoriteAnimal: ‘dog‘
    });
    peopleStore.put({
        name: "Jay", // name is the key
        age: 24,
        favoriteAnimal: ‘dog‘
    });
    return tx.complete;
}).then(function () {
    console.log("People are added");
});

dbPromise.then(function (db) {
    var tx = db.transaction(‘people‘, ‘readwrite‘);
    var peopleStore = tx.objectStore(‘people‘);
    var ageIndex = peopleStore.index(‘age‘);
    return ageIndex.openCursor();
}).then(function (cursor) {
    if (!cursor) return;
    return cursor.advance(1); // skip the first person
}).then(function logPerson(cursor) {
    if(cursor.value.name == "Jie"){
        cursor.delete(); // delete
    }
    if(cursor.value.name == "Jay"){
        console.log("Cursor at:", cursor.value.name);
        var joe = cursor.value;
        joe.favoriteAnimal = "Bird";
        cursor.update(joe); // update
    }
    return cursor.continue().then(logPerson);
}).then(function () {
    console.log("DONE");
});

 

[PWA] 14. Loop cursor

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5503854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!