我最近开始使用backbone.js 进行测试。我有一个小应用程序,它应该从服务器获取数据,将数据转换为表单字段,然后将它们插入到表单中。不幸的是,当我去 render() 集合视图时,什么也没有发生。但是,页面加载后,如果我输入
fieldCollectionView.render();
进入控制台,神奇地渲染了我的字段。
这是我的应用程序代码。这是我期望工作的倒数第二行,但它没有:
var FieldModel = Backbone.Model.extend({
defaults: function(){
return {
type: "text",
}
},
});
var FieldCollection = Backbone.Collection.extend({
model: FieldModel,
url: "/register/Backbone/includes/JSONgetRegFields.js",
//parse: function(response){
// return response
//}
});
var FieldView = Backbone.View.extend({
tagName: "div",
className: "field_wrapper",
id: "field_wrapper1",
template: _.template( $("#field-template").html() ),
render: function() {
var attributes = this.model.toJSON();
this.$el.html( this.template(attributes) );
return this;
}
});
var FieldCollectionView = Backbone.View.extend({
initialize: function() {
},
addOne: function( fieldModel ) {
var fieldView = new FieldView({model: fieldModel });
//console.log(fieldView.render().el )
this.$el.append( fieldView.render().el );
},
render: function(){
this.collection.forEach(this.addOne, this);
//console.log(this)
}
});
var fieldCollection = new FieldCollection();
var fieldCollectionView = new FieldCollectionView({ collection: fieldCollection });
fieldCollection.fetch();
fieldCollectionView.render()
$("#formTarget").html( $(fieldCollectionView.el) );
这是我返回的 json 的样子:
[ { "label": "First Name", "fid": "FirstName", "fieldClasses" : "required", "labelClasses" : "requiredLabel"}
, { "label": "Last Name", "fid": "LastName", "fieldClasses" : "required", "labelClasses" : "requiredLabel"}
, { "label": "Email", "fid": "Email", "fieldClasses" : "required email", "labelClasses" : "requiredLabel"}
, { "label": "Confirm Email Please", "fid": "ConfEmail", "fieldClasses" : "required email", "labelClasses" : "requiredLabel"}
, { "label": "Fax", "fid": "Fax", "fieldClasses" : "number cdsphone", "labelClasses" : ""}
]
另外我应该注意,如果我使用
setTimeout( function() { fieldCollectionView.render() }, 120)
我的收藏视图也会渲染 - 但我觉得这不是一个很好的方法。我在这里哪里出错了?