Reputation: 16491
I have a collection where the data is returned looking like:
{
"departments": ["Customer Support", "Marketing"],
"classes": ["Planning", "Drawing"]
}
I'm not overly sure how to use underscore template loops to output each of the departments, right now I'm using ._each
but my output is object Object
. Can anyone advise how to resolve this?
Fiddle: http://jsfiddle.net/kyllle/aatc70Lo/7/
Template
<script type="text/template" class="js-department">
<select>
<% _.each(departments, function(department) { %>
<option value="<% department %>"><% department %></option>
<% }) %>
</select>
</script>
JS
var Department = Backbone.Model.extend();
var Departments = Backbone.Collection.extend({
model: Department,
parse: function(response) {
return response;
}
});
var DepartmentView = Backbone.View.extend({
template: '.js-department',
initialize: function() {
console.log('DepartmentView::initialize', this.collection.toJSON());
},
render: function() {
this.$el.html( this.template( this.collection.toJSON() ) );
}
});
var departments = new Departments({
"departments": ["Customer Support", "Marketing"]
}, {parse:true});
var departmentView = new DepartmentView({
collection: departments
});
document.body.innerHTML = departmentView;
Upvotes: 1
Views: 81
Reputation: 2721
render()
, so your template is never even executed, and the object Object
output has nothing to do to your template.render()
you will realizetemplate: '.js-department'
template: _.template($('.js-department').html())
this.collection
is an array, that only has one item, so if you just want to render that first item, you will send to it to template:this.$el.html( this.template( this.collection.first().toJSON() ) );
departmentView
is a Backbone.View instance object, and isn't html itself. It has the el
property which is the DOM element of this view instance, and $el
property, which is the same DOM element wrapped with jQuery.document.body.innerHTML = departmentView.el
still will not work, because innerHTML
expects a string. So you could instead do something likedocument.body.appendChild( departmentView.el );
ordepartmentView.$el.appendTo( document.body );
with jquery.render
must return this
)Working jsfiddle: http://jsfiddle.net/yuraji/zuv01arh/
Upvotes: 3