Pretty sure this has been asked already, but I don’t know what to search for. Anyway,
var livemarks = [];
var livemarkIds = PlacesUtils.annotations.getItemsWithAnnotation("livemark/feedURI", {});
for (var i = 0; i < livemarkIds.length; i++){
PlacesUtils.livemarks.getLivemark( {id : livemarkIds[i]}, function(result, livemark){
if (result == Components.results.NS_OK){
livemarks.push(livemark);
}
});
}
alert(livemarks.length);
I am trying to play a bit with a Firefox addon that’s no longer maintained by its creator, just to learn a bit. I recently got an error saying getFeedURI is going to be deprecated and I want to change his old function.
EDIT:
From a function defined in a function (inner function), I am unable to access a var defined in the parent. Why?
E.g. I cannot access var livemarks from inside getLivemark(), or other similar internal functions.
I was checking (scroll down completely): this and his code works fine. So what’s wrong with my code? I just wanted to avoid the recursion, if possible.
I suspect the
PlacesUtils.livemarks.getLivemarkfunction does its work asynchronously, so your callback is called after you alert thelength. Put your alert inside the callback and you should see the correct length (eventually). Here’s one way:Note that there I put
livemarkIds.lengthintoexpecting, just in case you do other things withlivemarkIdswhile the function is running. If you aren’t, you can just use that directly.Re your comment below:
If
PlacesUtils.livemarks.getLivemarkis asynchronous, it’s impossible forgetFeedsto return the array as a return value. E.g., it cannot be used like this:The good news is it’s really easy to fix: Have
getFeedsaccept a callback function that it calls when it has the feeds. The code above changes to look like this:As you can see, it’s a pretty straightforward change. Assuming the loop above is all of
getFeeds, thengetFeedsends up looking something like this:And the pattern continues: If the code calling
getFeedsis being called by something else that’s expecting a return value from the async stuff, instead of returning that value, you have that code accept a callback, and call the callback from thegetFeedscallback. And so on.Once you get used to it, it’s very easy to do. Getting used to it can be tricky. 🙂