I apologize if this is rudimentary, but extensive googles and trolling through StackOverflow questions have gotten me workarounds but no answers. I am sure the answer is out there, I just don't where where there is.
I have been trying to make a simple Chrome Extension that can move around bookmarks. There are several points where I want to have a for-loop run up until the length of an existing object.
Here is a snippet of what I mean. Forgive me if my JavaScript hurts the eyes:
var book = {title:[], id:[], url:[], parentId:[], children:[], index:[]};
function getHier(id) {
obj = book.title.length;
chrome.bookmarks.getChildren(id, function (children) {
children.forEach(function (bookmark) {
book.title[obj] = bookmark.title;
book.id[obj] = bookmark.id;
book.url[obj] = bookmark.url;
book.parentId[obj] = bookmark.parentId;
book.children[obj] = bookmark.children;
book.index[obj] = bookmark.index;
obj += 1;
});
});
};
getHier('0');
getHier('1');
At this point, I would like to do something like this :
for(var i = 0, len = book.url.length; i <= len; i++){
//DO SOMETHING
}
The problem is, it doesn't run through the for-loop as I expected. But, if I made this a function, and called in the console AFTER I have loaded my extension, it works great. OR, if I use an integer in place of book.url.length
the code executes as I expect.
As a side note, I do have a document.addEventListener('DOMContentLoaded', function() {})
in the body of my script as well. While I don't believe it is part of the issue (I have commented it out and the problem sticks around), I thought it was worth mentioning.
My question is, at what point do my variables/objects become defined? Clearly book.url.length
is not defined when I try to refer to it in my for-loop. So when can I "refer back" to a value I have just set?
Update 1:
If I place the loop into a function, and call that function on a click
event within my document.addEventListener('DOMContentLoaded', function() {})
, the function executes my loop as expected. This, I assume, would be the same as calling the function in the console as the script is loaded before I can click any of my buttons; but this really isn't what I'd like to happen. I'll continue to update as I hack away at this, trivial as it may be, problem.