我最近将我的骨干js文件更新到最新版本,你知道什么东西正在破碎 - 太令人沮丧了。我在视图中实例化一个集合,我正在尝试遍历集合,但它只输出集合中的最后一项无法弄清楚为什么这里是我的代码
NavView = Backbone.View.extend({
el : $('ul'),
initialize: function(){
_.bindAll(this, 'render');
this.navCollection = new NavigationCollection([ {name: "home", href: '/home'},{name: "about", href:'/about'},{name: "contact", href: '/contact'}]);
this.render();
},
我尝试了很多方法来渲染下面的代码
render : function() {
this.navCollection.each(function (item) {
$(this.el).append("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>");
}, this);
return this; // remember this for chaining
//also tried this method as well
_.each(this.navCollection.models, function(item){
//$(this.el).append("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>");
$("<li><a href=" + item.get("href") + ">" + item.get("name") + "</a></li>").appendTo(this.el);
},this)
return this; // remember this for chaining
},
无论哪种方式,它只输出最后一个项目联系人而不是三个项目 见http://dalydd.com/projects/backbone/backbone.html
var NavigationItem = Backbone.Model.extend({
defaults: {
name: '',
href: '',
last: false,
id: ''
},
initialize: function() {
}
});
var NavigationCollection = Backbone.Collection.extend({
model: NavigationItem,
});
在输出所有内容之前,当我将主干更新到更新的版本时,它只打印出1 - 一如既往地感谢任何帮助。
谢谢
答案 0 :(得分:2)
在NavigationItem定义中,将id的默认值设置为空字符串:
var NavigationItem = Backbone.Model.extend({
defaults: {
name: '',
href: '',
last: false,
id: ''
}
});
在Backbone 0.9.9中,模型以相反的顺序添加duplicate models are rejected,一个空字符串被接受为有效ID,让您在集合中使用最后一个模型。删除id的默认值以解决您的问题
var NavigationItem = Backbone.Model.extend({
defaults: {
name: '',
href: '',
last: false
}
});