Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nmoliveira/5732262 to your computer and use it in GitHub Desktop.
Save nmoliveira/5732262 to your computer and use it in GitHub Desktop.
Example for rendering a Backbone.js collection using Handlebars.js
<html>
<head>
<title>Backbone Trainning</title>
</head>
<body>
<!-- Template -->
<script id="todos-tmpl" type="text/x-handlebars-template">
{{#each todos}}
<div class='todo-item'>
<p>Title: {{ this.title }} </p>
</div>
{{/each}}
</script>
<div id="listOfTodos"></div>
<!-- included scripts -->
<script src="scripts/jquery-1.10.0.js"></script>
<script src="scripts/underscore.js"></script>
<script src="scripts/backbone.js"></script>
<script src="scripts/handlebars.js"></script>
<script type="text/javascript">
// returns array of todos
function fakeTodos(){
var todos = [];
for (var i = 1; i <= 10; i++) {
var todo = new Backbone.Model({
title: 'Task ' + i,
})
todos.push(todo);
}
return todos;
}
// view for the list of todos
var ListView = Backbone.View.extend({
template: Handlebars.compile($('#todos-tmpl').html()),
render: function() {
debugger;
$(this.el).html(this.template({
todos: this.collection.toJSON()
}));
$('#listOfTodos').append(this.el);
return this;
}
});
$(function() {
// create todos
var todos = new Backbone.Collection(fakeTodos());
// the todos list
var todosList = new ListView({ collection: todos });
todosList.render();
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment