将大量字符串存储到IndexedDB中

时间:2015-02-12 03:06:15

标签: javascript arrays indexeddb

当我调用newCombs标签变为白色并且在Chrome任务管理器中消失时,我有一个名为store.put(game)的巨大数组。基本上这个过程就停止了,它无法存储数组

var trans = this.db.transaction('Games', 'readwrite');
var store = trans.objectStore('Games');
store.get(new Date().toLocaleDateString() + ' ' + prize.value).onsuccess = function() {
  var game = this.result;
  game.combs = game.combs.concat(newCombs); //I'm appending to the game.combs array which is empty when I first run it (when it also crashes)
  store.put(game);
}
trans.oncomplete = function(evt) {
  arrLength = 0;
  newCombs = [];
}

game等于:

game = {
   name: new Date().toLocaleDateString() + ' ' + prize.value,
   date: new Date().toLocaleDateString(),
   prize: prize.value,
   playerData: [...],
   points: {...}
}

上面的部分是一个对象的方法,所以this不是窗口对象,一切正常,直到代码遇到以下行:store.put(game);页面崩溃。

1 个答案:

答案 0 :(得分:1)

正如@paldepind建议您更改onsuccess事件处理程序中的范围并忽略自定义对象。

解决这个问题的一种方法是在定义匿名回调函数之前利用闭包并将this赋值给局部变量:

var trans = this.db.transaction('Games', 'readwrite');
var store = trans.objectStore('Games');
var that = this;
store.get(new Date().toLocaleDateString() + ' ' + prize.value).onsuccess =     function() {
  var game = that.result;
  game.combs = game.combs.concat(newCombs); 
  store.put(game);
}
trans.oncomplete = function(evt) {
  arrLength = 0;
  newCombs = [];
}