我正在使用一个包含书签标记系统信息的对象,该系统需要在 Chrome 会话中持续存在,因此我试图将其保存到本地存储中,并在创建新书签时对其进行更新。
当我创建一个新书签时,我会触发一个函数来查看现在是否有任何其他书签与新书签具有相同的标签。这将书签组织成“标签组”,其功能类似于动态文件夹。
当我设置存储对象时,正在存储的对象具有我期望的所有数据。但是,一旦我从存储中取出同一个对象,其中一个嵌套对象就会神秘地变成null
. 请参阅控制台输出:顶部对象就在 function 中的 set 调用之前updateStorage
。当我从存储中“获取”该对象时,底部是我得到的。请注意 tagGroups 书签现在为空。书签本身仍然存在,只是在标签组对象中它们才会消失。我花了一整天的时间来解决这个问题,试图让它发挥作用。
这是模型代码。我包含了上下文的所有内容,但最相关的部分是 createNewBookmark、updatePrimaryTreeWithTagGroups 和 updateStorage 方法。
更新:在设置/从存储中获取任何内容之前,我已经编辑了代码以对书签树进行所有更改,然后使用生成的对象进行最终调用以更新存储。我实际上是在存储一件事,一次,然后在我尝试检索时取回另一件事。
function PrimaryBookmarksTree(){
chrome.storage.sync.get(null, this.findOrCreate.bind(this));
}
PrimaryBookmarksTree.prototype.findOrCreate = function(result){
if (result.bookmarksTree != undefined){
this.bookmarks = result.bookmarksTree.bookmarks;
this.title = result.bookmarksTree.title;
this.tagGroups = result.bookmarksTree.tagGroups;
console.log(this);
} else {
this.bookmarks = [];
this.title = "Marinade Bookmarks";
this.tagGroups = [];
chrome.storage.sync.set({"bookmarksTree": this}, function(){console.log("New tree created!")});
console.log(this);
}
}
function Bookmark(name, tags, url){
this.name = name;
this.tags = tags;
this.url = url;
this.dateCreated = this.date();
}
function TagGroup(tag){
this.bookmarks = [];
this.tag = tag;
}
//called by controller when user tags a new bookmark via the extension
PrimaryBookmarksTree.prototype.createNewBookmark = function(name, tags, url){
var newBookmark = new Bookmark(name, tags, url);
this.bookmarks.push(newBookmark);
this.tagGroups = this.updatePrimaryTreeWithTagGroups();
this.updateStorage(this);
}
PrimaryBookmarksTree.prototype.updatePrimaryTreeWithTagGroups = function(){
var tagsForGrouping = this.getTagsWithMultipleBookmarks(this.bookmarks);
for(j=0;j<tagsForGrouping.length;j++){
this.tagGroups.push(this.buildTagGroup(tagsForGrouping[j]));
}
return this.tagGroups;
}
PrimaryBookmarksTree.prototype.getTagsWithMultipleBookmarks = function(bookmarks){
var tagsToCheck = this.pluck(bookmarks, "tags");
var tagCounts = tagsToCheck.reduce(function (obj, curr){
if (typeof obj[curr] == 'undefined') {
obj[curr] = 1;
} else {
obj[curr] += 1;
}
return obj;
}, {});
var tagGroups = this.filter(tagCounts, function(x){return x > 1});
return tagGroups;
}
PrimaryBookmarksTree.prototype.buildTagGroup = function(tag){
tagGroup = new TagGroup(tag);
for(i=0;i<this.bookmarks.length;i++){
if(this.bookmarks[i].tags[0] == tag){
tagGroup.bookmarks.push(this.bookmarks[i]);
}
}
if (tagGroup.bookmarks.length != 0){
return tagGroup;
}
}
PrimaryBookmarksTree.prototype.updateStorage = function(updatedTree){
console.log(JSON.stringify(updatedTree));
chrome.storage.sync.set({"bookmarksTree": updatedTree}, function(){console.log("final storage complete")});
}