Reputation: 5089
I'm working on my first backbone.js problems and I am having difficulty using collections. Judging from the console, the problem seems to be with outputting the collection view into the dom. The collection data is properly formatted in the console, its just not showing up in the browser. I can't figure what I am doing wrong:
var RegisterModel = Backbone.Model.extend({
urlRoot: 'api/process.php'
});
var RegisterView = Backbone.View.extend({
el: "#register",
template: _.template('<label for="<%= inputName %>"><%= label %></label><input name="<%= inputName %>" type="text" />'),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var RegisterCollection = Backbone.Collection.extend({
model: RegisterModel
});
var RegisterCollectionView = Backbone.View.extend({
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(registerModel){
var registerView = new RegisterView({model: registerModel});
this.$el.append(registerView.render().el);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
this.$el.empty();
},
render: function(){
this.addAll();
return this;
}
});
var registerCollection = new RegisterCollection();
var todos = [{inputName: "first_name", label: "First Name"}, {inputName: "last_name", label: "Last Name"}];
registerCollection.reset(todos);
var registerCollectionView = new RegisterCollectionView({collection: registerCollection});
registerCollectionView.render();
Upvotes: 0
Views: 209
Reputation: 161467
Here:
addAll: function(){
this.collection.forEach(this.addOne, this);
this.$el.empty();
},
You are calling empty()
after rendering each item. I assume you meant those two lines to be swapped around.
addAll: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
},
Also this:
el: "#register",
is wrong. You have multiple RegisterViews, so it does not make sense to be using an ID on that. Also, this will cause your logic to, instead of creating a new element for the view, to look for one already in the page. You should remove that line entirely.
What you do want is an el
on RegisterCollectionView
. Right now you do not attach that view to anything, so it is rendered but invisible.
You should be able to add this:
el: 'body'
Upvotes: 1