我相信这是以下问题的后续,因此我会将它们全部组合成一个在后台范围(background.js)中运行的单个代码示例:
实时与非事件编程,
crossrider:将书签的快照存储在本地数据库并与当前书签列表进行比较
所以对于getChanges函数,我更喜欢将书签树转换为哈希列表,然后比较列表的变化。在以下示例中,我使用createHash创建哈希列表,使用cloneNode创建节点对象的浅层克隆,然后在getChanges中比较哈希列表的添加、修改和删除:
appAPI.ready(function() {
// Poll every 30 seconds
setInterval(function() {
appAPI.db.async.get('prevBookmarks', function(value) {
// Load or initialize the previous bookmarks list
var prevBookmarks = (value) ? value : {};
// Get current bookmarks
appAPI.bookmarks.getTree(function(nodes) {
// Save bookmark hash for comparison in next interval
appAPI.db.async.set('prevBookmarks', createHash(nodes[0]));
// Get hash list of curent bookmarks
var currBookmarks = createHash(nodes[0]);
// Get changes between the lists
var changes = getChanges(prevBookmarks, currBookmarks);
// Post changes to your API server
appAPI.request.post({
url: http://yourAPIserver.com,
postData: changes,
contentType: 'application/json'
});
});
});
}, 30 * 1000);
// Function to create a hash list from a bookmark tree
function createHash(node) {
var hash = {};
if (typeof node === 'object') hash[node._id] = cloneNode(node);
if (node.isFolder && typeof node.children !== 'undefined' && node.children.length > 0) {
node.children.forEach(function(child) {
var childHash = createHash(child);
for (var key in childHash) {
if (!hash[key]) hash[key] = cloneNode(childHash[key]);
}
});
}
return hash;
}
// Function to create shallow clones of bookmark nodes
function cloneNode(node) {
var clone = appAPI.JSON.parse(appAPI.JSON.stringify(node));
delete clone.children;
delete clone.dateAdded;
return clone;
}
// Get changes between current and previous bookmark hash lists
function getChanges(prev, curr) {
// Initialize return object
var changes = {added:{}, modified:{}, removed:{}};
// Search for added or modified nodes
for (var key in curr) {
if (!prev[key])
changes.added[key] = curr[key];
else if (appAPI.JSON.stringify(prev[key]) !== appAPI.JSON.stringify(curr[key]))
changes.modified[key] = curr[key];
}
// Search for removed nodes
for (var key in prev) {
if (!curr[key])
changes.removed[key] = prev[key];
}
return changes;
}
});
免责声明:我是 Crossrider 的员工