ac360
ac360

Reputation: 7835

Javascript variable showing up as undefined in Backbone

At the top of my page, I grab a value of a hidden input field, store it as a variable, then try to use it in my Backbone code. But, the value shows up undefined. How can I get the value of the field first, and then initialize my backbone app?

<script>
$(document).ready(function(){

    var whitedealsToken = $('#usertoken').val();
    console.log(whitedealsToken)

    WhiteDeals.initialize();

});
</script>

EDIT: Full Backbone Code Below

window.WhiteDeals = {
  Models: {},
  Collections: {},
  Views: {},
  Routers: {},
  initialize: function() {
    new WhiteDeals.Routers.Deals();
    if (!Backbone.history.started) {
        Backbone.history.start();
        Backbone.history.started = true;
    }
  }
};

WhiteDeals.Routers.Deals = Backbone.Router.extend({

 routes: {
            "":   "index"
     },

     index: function() {
       var deals = new WhiteDeals.Collections.Deals();
       var dealsview = new WhiteDeals.Views.DealsIndex({
        el: $('#container')
       });
     }

});

WhiteDeals.Collections.Deals = Backbone.Collection.extend({

  model: WhiteDeals.Models.Deal,
  url: 'http://lvh.me:3000/api/v1/special_deals?access_token=' + whitedealsToken,
  parse: function(response) {
  return response.results;
  },
  // Overwrite the sync method to pass over the Same Origin Policy
  sync: function(method, model, options) {
     var that = this;
     var params = _.extend({
         type: 'GET',
         dataType: 'jsonp',
         url: that.url,
         processData: false
     }, options);

    return $.ajax(params);
  }

 }); // End Collection

Upvotes: 1

Views: 391

Answers (2)

kinakuta
kinakuta

Reputation: 9037

You're referencing whitedealsToken in your extend call which is executing essentially as soon as the script runs. Since whitedealsToken isn't actually being assigned a value until $(document).ready, it's going to be undefined where you're trying to use it. You would need to put your .extend call inside the same $(document).ready block after you've assigned a value to the variable in question.

Upvotes: 1

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

When you declare a variable in a function, it is only available in the local scope. So outside of that function it does not exist.

Check out this link: http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx

You could instead make it global:

whitedealsToken = $('#usertoken').val();  // no var keyword

Or make it a property of some other global object:

WhiteDeals.whitedealsToken = $('#usertoken').val();

Or pass it into your initialize method and do something like this:

var whitedealsToken = $('#usertoken').val();
console.log(whitedealsToken)

WhiteDeals.initialize(whitedealsToken);

This last one by itself would not fix it, you would have to do some more work to pass the token into the instantiated collection at some point.

Upvotes: 1

Related Questions