Reputation: 1618
This should be simple but I've been stuck for about 3 hours on it, and can't seem to find a solution. I'm new to backbone so maybe I'm overlooking something.
I'm trying to render a view where the options all have values. It's coming out like this:
<select name="role" id="option-roles" class="form-control">
<option>All</option>
<option>Basic User</option>
<option>Basic Student</option>
...
</select>
But I want each option to have a value to look like this:
<option value='10'>Basic User</option>
In backbone my code looks like this.
app.RoleSelectView = Backbone.View.extend({
el: '#roles',
template: _.template($('#tmpl-roles').html()),
initialize: function() {
this.collection = new Backbone.Collection(app.mainView.results.roles, {
model: app.Role
});
this.render();
},
render: function() {
this.$el.html(this.template());
var frag = document.createDocumentFragment();
var view = new app.RoleOptionsView({
model: new app.Role(),
value: ''
});
frag.appendChild(view.render().el);
this.collection.each(function(role) {
var view = new app.RoleOptionsView({
model: role,
value: role.id.toString()
});
frag.appendChild(view.render().el);
}, this);
$('#option-roles').append(frag);
return this;
}
});
app.RoleOptionsView = Backbone.View.extend({
tagName: 'option',
template: _.template($('#tmpl-role-option').html()),
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
Any help would be appreciated.
Upvotes: 0
Views: 504
Reputation: 434705
From the fine manual:
el
view.el
[...]
this.el
can be resolved from a DOM selector string or an Element; otherwise it will be created from the view'stagName
,className
,id
andattributes
properties.
If you want to add an attribute (such as value
) to your el
then use attributes
:
app.RoleOptionsView = Backbone.View.extend({
tagName: 'option',
attributes: function() { // <---------------------------------
return {
value: 'where ever your value comes from'
};
},
template: _.template($('#tmpl-role-option').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON());
return this;
}
});
Also, it is generally preferred that you say this.model.toJSON()
rather than directly accessing this.model.attributes
.
Like most data-ish things in views, the attributes
can either be a static object or a function which returns an object. In your case, the attributes presumably depend on something in the view's model so a function is needed so that you can work with the view instance and its model.
Upvotes: 1