Skip to content Skip to sidebar Skip to footer

Scope In JavaScript / JQuery

I've clearly been writing too much CoffeeScript, as I am now realizing I do not have even a basic understanding of scope in pure JS. After playing for a while, I cannot figure out

Solution 1:

The reason photos is undefined is not because of scopes. Its because $.get is executed asynchronously. $.get() returns jqXHR object instead of an HTTP response.

onSuccess callback should be passed to getPhotos() in order to make it work correctly. Alternatively when().then() construct could be used.

$(document).ready(function() {
    var myUrl = "http://example.com/";
    getPhotos(myUrl, renderCatPhotos);    
});

function getPhotos(url, onSuccess) {
    $.get(url, onSuccess);
}

function renderCatPhotos(data) {
    var a = data.photoset.photo;
    console.log(a);  // a is always available
}

note: you might not even need getPhotos function. You can simply $.get(url, onSuccess); in $(document).ready() instead.


Solution 2:

Its not a matter of scope, its a matter of that you are returning an undefined variable before the $.get defines it. Consider making photos a global, then setting it in the $.get success function instead of setting it to 'a'. Inside the success function, you can then issue calls to other functions that would control displaying/processing the photos.


Post a Comment for "Scope In JavaScript / JQuery"