Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created November 28, 2011 09:11
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save simenbrekken/1399715 to your computer and use it in GitHub Desktop.
Save simenbrekken/1399715 to your computer and use it in GitHub Desktop.
Backbone.js child views example
var View = Backbone.View.extend({
tagName: 'tr',
template: Handlebars.compile($('#project-list-item').html()),
events: {
'click .delete': 'destroy'
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
destroy: function(e) {
if (confirm('Are you sure you want to delete this?')) {
this.model.destroy();
}
},
remove: function() {
$(this.el).remove();
}
});
<script id="project-list-item" type="text/x-handlebars-template">
<td><a class="name" href="#projects/{{_id}}/edit">{{name}}</a></td>
<td class="operators">
<a class="btn small delete">Delete</a>
<a class="btn small edit" href="#projects/{{_id}}/edit">Edit</a>
</td>
</script>
<section class="list view">
<h1>Your projects</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody class="container">
</tbody>
</table>
<div class="actions">
<a href="#projects/add" class="btn primary">New project</a>
<a class="btn delete-selected">Delete selected</a>
</div>
</section>
var View = Backbone.View.extend({
initialize: function() {
this.collection.bind('add', this.add, this);
this.collection.bind('reset', this.reset, this);
},
render: function() {
_(this.collection.models).each(this.add, this);
return this;
},
add: function(project) {
var itemView = new ListItem({ model: project });
itemViews.push(itemView);
this.$('.container').append(itemView.render().el);
},
reset: function() {
$container.empty();
this.render();
}
}
@bflemi3
Copy link

bflemi3 commented Sep 7, 2017

projects.js line 15 - itemViews isn't defined, but how would you use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment