我(作为初学者)制作一个小骨干函数来附加我的链接,为此我使用该集合分配模型,
但是这个集合会抛出错误..任何人都可以纠正我的代码吗?
$(function(){
var Model = new Backbone.Model({
data:[
{name:'Yahoo',href:'http://www.yahoo.com'},
{name:'Gmail',href:'http://www.gmail.com'},
{name:'Bing',href:'http://www.bing.com'}
]
});
var Collection = new Backbone.Collection.extend({
model:Model // is this not correct way to do?
});
var View = Backbone.View.extend({
el:'#container',
events:{
'click button':'render'
},
initialize:function(){
this.collection = new Collection(); //throw the error!
this.template = $('#temp').children();
},
render:function(){
var data = this.collection.get('data');
for(i=0;i<data.length;i++){
var li = this.template.clone().find('a')
.attr('href',data[i].href)
.text(data[i].name).end();
this.$el.find('ul').append(li);
}
}
});
var myLink = new View();
})
答案 0 :(得分:2)
模型用于存储和管理单个数据块。在你的情况下,这将是一个单一的名称/ href对。通常使用Backbone.Model.extend
创建包含所有特定于模型的方法和属性的模型“类”,然后使用new
创建该模型的实例,或将该模型“class”设置为集合{{ 3}}以便集合可以创建模型的新实例。
您的模型看起来应该更像这样:
var Model = Backbone.Model.extend({
defaults: {
name: '',
href: ''
}
});
请注意,那里没有new
,因为我们只是建立了一个基于我们的模型实例的“类”。然后我们将模型挂钩到一个集合(再次使用extend
而没有new
):
var Collection = Backbone.Collection.extend({
model: Model
});
现在你可以model
property并为模型提供一系列数据:
var links = new Collection([
{ name: 'Yahoo', href: 'http://www.yahoo.com' },
{ name: 'Gmail', href: 'http://www.gmail.com' },
{ name: 'Bing', href: 'http://www.bing.com' }
]);
您经常将集合传递给视图,而不是让视图实例化集合;如果您说this.collection
,create an instance of the collection设置new SomeView({ collection: some_collection })
,那么您可以:
var View = Backbone.View.extend({
//...
initialize: function() {
this.template = $('#temp').children();
},
并说出new View({ collection: links })
并通过视图中其他位置的this.collection
访问该集合。
一个集合是几个模型的集合(有点像数组),它将有Backbone will automatically,所以你可以像这样遍历集合:
render: function() {
this.collection.each(function(link) {
var li = this.template.clone().find('a').attr('href', link.get('href')).text(link.get('name'));
this.$('ul').append(li);
}, this);
}
还要注意使用various useful Underscore methods mixed in来访问模型属性,模型属性和对象属性是不同的东西。您还可以使用get
一次展平所有数据。 toJSON
的最终this
参数使回调内的this
成为视图。 Backbone已经在视图的each
方法中提供了this.$el.find()
别名,所以我也切换到了。{/ p>
这是一个简化的演示:this.$()