Backbone.js对Underscore模板的未捕获ReferenceError

时间:2014-11-01 08:47:25

标签: javascript jquery json backbone.js underscore.js

我有一个Backbone应用程序。

我的json看起来像这样,

{
  "cities": [
    "Kävlinge",
    "Lund",
    "Enskede",
    "Vadstena"
  ]
}

My Backbone Collection Code

var Cities = Backbone.Collection.extend({
  url: 'configuration/city.json'
});

var Index = Backbone.View.extend({
  initialize: function(){
    this.cities = new Cities();
  },
  el: '.page',
  render: function(){
    var self = this;
    this.cities.fetch({
      success: function(cities){
        console.log(cities.models[0].attributes.cities);
        var template = _.template($('#city-dropdown').html(),{cities: cities.models[0].attributes});
        self.$el.html(template());
      }
    });
  }
});

var Router = Backbone.Router.extend({
  routes: {
    '' : 'home'
  }
});
var router = new Router();

var index = new Index();
router.on('route:home',function(){
  index.render();
});

Backbone.history.start();

在下划线模板函数之前的console.log语句打印我所需的Json数组,但是在我的脚本标记中,它只是未捕获的ReferenceError:未定义城市,

我的Json不正确,或者我的Backbone代码不正确,我感到困惑。看起来很傻。请协助。

  <script type="text/template" id="city-dropdown">
      <select class="selectpicker">
        <%=  _.each(cities, alert) %>
      </select>
    </script>

1 个答案:

答案 0 :(得分:1)

截至下划线1.7.0:

  

下划线模板不再接受初始数据对象。 _.template现在总是返回一个函数。

所以现在_.template函数的第二个可选参数用于设置模板选项。将对象传递给编译函数:

var template = _.template($('#city-dropdown').html());
self.$el.html(template({
   cities: cities.models[0].attributes // cities.toJSON()
}));