1

在我的页面顶部,我获取了一个隐藏输入字段的值,将其存储为一个变量,然后尝试在我的 Backbone 代码中使用它。但是,该值显示为未定义。如何先获取字段的值,然后初始化我的主干应用程序?

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

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

    WhiteDeals.initialize();

});
</script>

编辑:下面的完整骨干代码

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
4

2 回答 2

1

在函数中声明变量时,它仅在本地范围内可用。因此,在该功能之外它不存在。

查看此链接: http: //msdn.microsoft.com/en-us/library/ie/bzt2dkta (v=vs.94).aspx

您可以改为将其设为全局:

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

或者使它成为其他一些全局对象的属性:

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

或者将它传递到您的initialize方法中并执行以下操作:

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

WhiteDeals.initialize(whitedealsToken);

最后一个本身并不能解决它,您必须做一些更多的工作才能在某个时候将令牌传递到实例化的集合中。

于 2013-03-28T05:12:12.227 回答
1

whitedealsToken在扩展调用中引用,该调用基本上在脚本运行后立即执行。因为whitedealsToken直到 $(document).ready 才真正被赋值,所以它在你试图使用它的地方是未定义的。在为相关变量赋值后,您需要将 .extend 调用放在同一个 $(document).ready 块中。

于 2013-03-28T07:02:25.690 回答