Created
November 28, 2011 09:11
-
-
Save simenbrekken/1399715 to your computer and use it in GitHub Desktop.
Backbone.js child views example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
projects.js line 15 - itemViews isn't defined, but how would you use it?