Reputation: 699
I have just started a POC on backbone.js and facing a basic problem.I am populating a dropdown list using a collection. But the dropdwon is not getting populated with the static values defined in the collection.
Can you please help me out on this.
$(function () {
var Country = Backbone.Model.extend();
var Countries = Backbone.Collection.extend({
model: Country
});
var CountryView = Backbone.View.extend({
tagName: "option",
initialize: function () {
_.bindAll(this, 'render');
},
render: function () {
$(this.el).attr('value',
this.model.get('id')).html(this.model.get('name'));
return this;
}
});
var CountriesView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'addOne', 'addAll');
this.collection.bind('reset', this.addAll);
},
addOne: function (country) {
$(this.el).append(
new CountryView({ model: country }).render().el);
},
addAll: function () {
this.collection.each(this.addOne);
}
});
var countries = new Countries([{
id: 'US',
name: 'US'
},
{
id: 'India',
name: 'India'
},
{
id: 'UK',
name: 'UK'
}]);
var countriesview = new CountriesView({ el: $("#country"), collection: countries });
//countries.fetch();
});
Upvotes: 2
Views: 3416
Reputation: 22375
It looks like your render method was never getting called because the collection's reset
wasn't being fired. Here's a fiddle in which I'm calling collection.reset
with your model data after the countriesview
is created. There is a console.log
statement in render, and you should see that it fires.
countriesview.collection.reset([{
id: 'US',
name: 'US'
},
{
id: 'India',
name: 'India'
},
{
id: 'UK',
name: 'UK'
}]);
I think there is probably an event that fires when the view is first created, and that you will need to render the view in response to that.
Edit: actually, no, why would there be? Backbone's view is just that: a view. The only logic it encapsulates is showing itself. It doesn't know that it is a collection view, so it doesn't respond to being instantiated with a collection. Probably you want to add some logic in the constructor to get the collection view started (or do as I've done here and call reset to populate the collection). I'm used to using Marionette in addition to backbone. Marionette gives you just enough specialization around views that you don't need to worry as much about creating custom backbone views to handle collections, etc.
Upvotes: 1