我有一个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>
答案 0 :(得分:1)
截至下划线1.7.0:
下划线模板不再接受初始数据对象。
_.template
现在总是返回一个函数。
所以现在_.template
函数的第二个可选参数用于设置模板选项。将对象传递给编译函数:
var template = _.template($('#city-dropdown').html());
self.$el.html(template({
cities: cities.models[0].attributes // cities.toJSON()
}));