Aniruddh Bhagwat
Aniruddh Bhagwat

Reputation: 37

underscore.js no data outside _.each

I'm retrieving a JSONp file with jQuery's $.ajax. I can't figure out how to make the underscore loop work...

in success I've this this code:

                success : function(response) {

                        var dataResp = '';
                        _.each(response.results, function(response, index) {

                                    var dataResp = response;

                                    var prodName = dataResp.trackName;
                                    var prodUri = dataResp.trackViewUrl;
                                    var prodUri = dataResp.trackViewUrl;
                                    var prodUri = dataResp.trackViewUrl;
                                    var prodPrice = Math.round(dataResp.trackPrice);
                                    var prodImg = dataResp.artworkUrl100.replace("100x100bb.", "700x700bb.");

                                    console.log(prodName); // returns all product names, and that's fine

                        }, this);

                        console.log(dataResp); // dataResp is empty


                                var html = "";
                                var compiled = _.template($("#product-structure").html(), dataResp );

                                _.each(dataResp, function(data) { // loop to compile template for all the elements inside the jsonp response
                                  html += compiled(data);
                                });

                                $('#data').html(html); // append to html the compiled template


                }

I use underscore.js for the templating part but I can't figure out why my data isn't available outside that _.each loop...

here my template:

<script type="text/template" id="product-structure">
<%= data.img %>
<%= data.title %>
<%= data.price %>
<%= data.uri %>
</script>

Upvotes: 0

Views: 200

Answers (2)

fayzaan
fayzaan

Reputation: 265

you can use the _.map function which returns a new array. I am assuming you want an object returned with those values.

This code will return an array of objects, each object will contain the prodName, prodUri, prodPrice, and prodImg.

var dataResp = _.map(response.results, function(response, index) {
    return {
        prodName: response.trackName,
        prodUri: response.trackViewUrl,
        prodPrice: Math.round( response.trackPrice ),
        prodImg: response.artworkUrl100.replace( "100x100bb.", "700x700bb")
    };
}, this);

Upvotes: 0

Dylan Harness
Dylan Harness

Reputation: 729

You have use the var keyword twice. Inside the loop you have:

var dataResp = response; which creates a new variable called dataResp. Since variables have function scope in js, this variable only exists in the function in which it is created. The solution is to switch it to dataResp = response; without the var

Upvotes: 0

Related Questions