1

In the following code snippet I've declared the variable "id" within the submit function. I attempt to assign a value to it within a nested function but it doesn't appear to be within scope and I don't know why.

$(document).ready(function() {
if (typeof(localStorage) == 'undefined' ) {
    alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} 
else {

    $("#logForm").submit(function(){
        var id;

        chrome.bookmarks.getRecent(1, function(mostrecent) {
            getLastId(mostrecent);
            });

        function getLastId(mostrecent) {
            mostrecent.forEach(function(mostrecent) {
                lastId = mostrecent.id;
                alert(lastId + ' was last id');
                id = lastId;
                })
            }
        alert(id + ' outside function');

Bonus Question - If you know a better way to pull the last-used id from chrome for a bookmark would love to know what it is. I had to pull recent which doesn't account for the possibility of an added and then deleted last bookmark which would have incremented the index.

4
  • @ Šime - Is there a lint for ECMA 5? Commented Apr 9, 2011 at 22:24
  • JSLint is for EcmaScript 5, too. Commented Apr 9, 2011 at 22:30
  • You forgot to declare the lastId variable. Commented Apr 9, 2011 at 22:33
  • missing semicolon on the forEach. Commented Jan 7, 2012 at 14:58

1 Answer 1

2

This should do it:

$("#logForm").submit(function() {

    var id;

    chrome.bookmarks.getRecent(1, function(arr) {
        id = arr.pop().id;
    });

    // do stuff with id

});
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for noticing that. I'm struggling with the asynchronous functions required by the chrome api quite a bit. Do you know how to verify the value assignment has been made before attempting to use the variable?
@Korak If the callback is asynchronous, you have to continue your code inside the callback body. If the callback is synchronous, your can continue your code below the callback. So it depends...
@Šime Maybe I'm going about this the wrong way somehow. My goal is to get the id on the last node from the chrome bookmarks api which requires the usage of an asynchronous function. Is there a better way to assign, pass, or return that value than what I am doing?
@Šime just thought I would post to let you know that I've been able to move enough of the action inside the function to make it work. Thanks for the help!
@Šime Thanks a lot for all your help. Will be dealing with these issues on an ongoing basis so your answer will help with a bunch of variable extractions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.