我在下面的骨干代码中显示了html页面上的模型列表。但是,模型是静态创建的,我必须对下面的代码进行哪些修改才能获取JSON数据并根据收到的数据创建模型。
var Person = Backbone.Model.extend({
defaults: {
name: "John Doe",
age: 27,
designation: "worker"
},
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
},
validate: function(attrs){
if(attrs.age < 0){
return 'Age must be positive,stupid';
}
if( ! attrs.name ){
return 'Name should not be empty';
}
},
work: function(){
return this.get('name') + ' is a ' + this.get('designation');
}
});
var PersonCollection = Backbone.Collection.extend({
model: Person
});
var peopleView = Backbone.View.extend({
tagName: 'ul',
render: function(){
//filter through all the items in a collections
//for each, create a new PersonView
//append it to root element
this.collection.each(function(person){
//console.log(person);
var personView = new PersonView({model:person});
this.$el.append(personView.render().el);
},this);
$(this.$el).appendTo('body');
}
});
// The view for a Person
var PersonView = Backbone.View.extend({
tagName : 'li',
className : 'person',
id : 'person-id',
template: _.template( $('#personTemplate').html() ),
initialize : function(){
_.bindAll(this,'render');
//console.log(this.model)
this.render();
},
render: function(){
$(this.$el.html(this.template(this.model.toJSON()))).appendTo('body');
return this;
}
});
var modelperson = new Person;
var viewperson = new PersonView({collection:new PersonCollection(),model : modelperson});
var personCollection = new PersonCollection([
{
name: "raghu",
age:24,
designation: "CEO"
},
{
name: "shashank",
age:23,
designation: "CTO"
},
{
name : "junaid",
age : 30,
designation : "UI"
},
{
name: "vishnu",
age: 23,
designation: "content developer"
}
]);
var pw = new peopleView({collection: personCollection});
pw.render();
html
<script type="text/template" id="personTemplate">
<div class="row">
<div class="cell"><%= name %></div>
<div class="cell"><%= age %></div>
<div class="cell"><%= designation %></div>
</div>
</script>
测试jsfiddle http://jsfiddle.net/HVqMs/1/
答案 0 :(得分:0)
你的意思是拿到收藏品?这是一个简单的例子
var Group = Backbone.Model.extend( {
urlRoot: Constants.URL_PREFIX+'/api/v1/group',
});
var GroupCollection = Backbone.Collection.extend( {
url: Constants.URL_PREFIX+'/api/v1/group',
model: Group,
parse(response){
this.metaData = new Backbone.Model(response.meta);
return response.objects;
}
});
then to fetch the collection lets call it MyCollection
var p = new GroupCollection();
p.fetch().done( function() {
p.each(function(item){
console.log(item.get('name'));
});
});
在我的例子中,json返回的是这样的
{
metaData:{ size:10,limit:10},
objects:[{name:'pep',id:1},{name:'pep2',id:2}]
}
这就是为什么我重写解析。