如何从indexedDB获取对象存储? [英] How to get objectstore from indexedDB?

查看:358
本文介绍了如何从indexedDB获取对象存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的应用程序上为Web存储添加了indexdDb.

I have indexedDb on my app for web storage.

我想从下面的代码中获取商店.

I would like to get the store form the below code.

var store = myapp.indexedDB.db.transaction(['tree_nodes'],'readwrite').objectStore('tree_nodes'); 

它返回错误.众所周知,我打开了indexeddb数据库并进行了版本更改.

It returns error. I was well known of opening indexeddb database and version changing.

错误是Uncaught TypeError: Cannot call method 'transaction' of null

我在断点处尝试过.在这种情况下,它可以正常工作而不会出错.

I was tried it with the break point. In that case it works fine without errors.

我如何去商店?请帮助我.

How can i get the store? please help me.

提前谢谢!

推荐答案

该错误可能是因为您的db变量为null.这几乎总是因为您试图通过回调将db存储在全局变量中,然后在一个单独的函数中访问db变量,该函数不能保证仅在设置db变量后才执行,例如浏览器发现您正在访问未初始化的变量.

The error is probably because your db variable is null. This is almost always because you are trying to store db in a global variable as a result of a callback, and then access the db variable in a separate function that is not guaranteed to only execute after your db variable is set, such that the browser finds you are accessing an uninitialized variable.

解决方案很简单(但令人沮丧).除非您想了解某些库的Promise和Deferd对象的实现,否则不能以这种方式使用全局变量.相反,请看Deni给出的答案.使用回调,并在回调函数(而不是全局变量)中编写代码.只能从回调request.onsuccess函数内部访问"db",而不是全局的.这就是Deni's会工作的原因.他的代码仅在保证已初始化(不为null)时才尝试访问db.

The solution is simple (but frustrating). You cannot use a global variable in this manner unless you want to learn about some library's implementation of promises and deferred objects. Instead, look at the answer given by Deni. Use callbacks and write your code in callback functions, not global variables. 'db' is only accessed from within the callback request.onsuccess function, and is not global. That's why Deni's will work. His code will only attempt to access db when it is guaranteed to be initialized (not null).

由于您没有发布周围的代码,事实证明这很重要,因此您需要执行以下操作:

Since you didn't post your surrounding code, which turns out to be important, you will need to do something like this:

// I am an evil global variable that will not work as expected
myapp.indexedDB.db = 'DO NOT USE ME OR YOU WILL GET AN ERROR';

// I am a good function that only accesses an initialized db variable
function doit() {
  var request = window.indexedDB.open(......);
  request.onsuccess = function(event) {
    // Use this db variable, not your global one
    var db = event.target.result;

    // Note that you can also access the db variable using other means
    // here like this.result or request.result, but I like to use event.target
    // for clarity.

    // Now work with the db variable
    var store = db.transaction(['tree_nodes'],'readwrite').objectStore('tree_nodes');
    // do some more stuff with store....
  };
}

这篇关于如何从indexedDB获取对象存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆