I try to render a list of item using underscore's template. But it displays nothing.
I tried to create 2 views, one is a task and one is a task list, but I'm stuck at using template.
- What does
.render()
do? - if I use template, do I still need to render?
I thought the data will map the template variable when you do this.$el.html(template_var)
?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script type="text/template" id="task_list">
<li><%=title%></li>
<li><%=priority%></li>
</script>
</script>
<script type="text/javascript">
(function(){
window.App = {
Models:{},
Collections:{},
Views:{}
};
window.template = function(id){
return _.template( $('#' + id).html() );
}
App.Models.Task = Backbone.Model.extend({
title: 'default',
priority: 1
});
App.Collections.Task = Backbone.Collection.extend({
model: App.Models.Task
});
App.Views.Task = Backbone.View.extend({
template: template('task_list'),
render(){
var template = this.template( this.model.toJSON() );
console.log(template)
this.$el.html(template);
return this;
}
})
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
render: function(){
this.collection.each( this.addOne, this);
return this;
},
addOne: function(task){
var taskView = new App.Views.Task({ model: task})
taskView.render();
this.$el.append(taskView.render().el);
}
})
var tasks = new App.Collections.Task([
{
title: 'Go to store',
priority: 4
},
{
title: 'Eat',
priority: 3
},
{
title: 'Sleep',
priority: 4
}
])
var tasksView = new App.Views.Tasks({collection: tasks})
$('body').html(tasksView.el)
})()
</script>
</body>
</html>