2
加載視圖時,集合長度總是返回1,而當前有3個成員出現在解析函數中。我想知道如果問題是嵌套的項目視圖,但它似乎沒有行爲!我不明白爲什麼self.push(成員)不會將模型添加到集合中!有點卡在這裏,請幫忙嗎?骨幹集合長度始終設置爲嵌套視圖
模型
define([
'backbone'
], function(Backbone) {
'use strict';
var MemberModel = Backbone.Model.extend({
id: "_id"
});
return MemberModel;
});
收集
define([
'backbone',
'models/MemberModel'
], function(Backbone, MemberModel) {
'use strict';
var Members = Backbone.Collection.extend({
model: MemberModel,
url: '/api/v1/users',
parse: function(response, options) {
var self = this;
_.each(response.users, function(item){
var member = new self.model();
member.set('email', item.email);
member.set('firstname', item.firstname);
member.set('lastname', item.lastname);
member.set('group', item.group);
member.set('city', item.city);
// shows every member's emails
console.log('member.email='+member.get('email'));
self.push(member);
});
console.log('this.length='+this.length); // this is always equal to 1
return this.models;
}
});
return Members;
});
視圖
define([
'collections/members',
'views/membersItem',
'text!templates/members.html'
], function(MembersCollection, MembersItem, membersTpl) {
'use strict';
var Members = Backbone.View.extend({
el: '#settings-content',
template: _.template(membersTpl),
events: {
'click #edit-member': 'editMember'
},
initialize: function() {
this.collection = new MembersCollection();
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
var self = this;
this.collection.fetch({
success: function() {
self.renderMember();
}
});
return this;
},
renderMember: function() {
// same here collection length = 1
console.log('collection.length:'+this.collection.length);
_.each(this.collection.models, function (item) {
var memberView = new MembersItem({model: item});
$('.list-item', this.el).append(memberView.render().el);
}, this);
}
});
return Members;
});
嵌套項目視圖
define([
'text!templates/members_item.html'
], function(membersItemTpl) {
'use strict';
var MembersItem = Backbone.View.extend({
tagName: "tr",
className: '.item',
template: _.template(membersItemTpl),
initialize: function() {
this.model.bind("change", this.render, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
return MembersItem;
});
該死!非常感謝。你救了我的一天:) – Kevin