Composite View: Grid View
A grid view build w/ Marionette
by dbouwman
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.modelbinding/master/backbone.modelbinding.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.memento/master/backbone.memento.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.marionette/master/lib/backbone.marionette.js"></script>
<script id="grid-template" type="text/template">
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
</tr>
</thead>
<tbody></tbody>
</script>
<script id="row-template" type="text/template">
<td>
<a href='#'><%= username %></a>
</td>
<td>
<%= fullname %>
</td>
</script>
<div id="grid">
</div>
<button id="reset">Reset</button>
CSS
table, tr, td, th, thead {
padding: 5px;
margin: 5px;
border: 2px solid #ccc;
}
thead {
background-color: #555;
color: #fff;
}
JavaScript
// A Grid Row
var GridRow = Backbone.Marionette.ItemView.extend({
template: "#row-template",
tagName: "tr",
events:{'click':'onClick'},
onClick: function(evt){
console.log(this.model.get('username'));
}
});
// The grid view
var GridView = Backbone.Marionette.CompositeView.extend({
tagName: "table",
template: "#grid-template",
itemView: GridRow,
appendHtml: function(collectionView, itemView){
collectionView.$("tbody").append(itemView.el);
}
});
// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
var userData = [
{
username: "dbailey",
fullname: "Derick Bailey"
},
{
username: "jbob",
fullname: "Joe Bob"
},
{
username: "fbar",
fullname: "Foo Bar"
}
];
var userData2 = [
{
username: "jmorten",
fullname: "Jeff Morten"
},
{
username: "geeser",
fullname: "larry flynt"
},
{
username: "goose",
fullname: "luke skywalker"
}
];
var User = Backbone.Model.extend({});
var UserCollection = Backbone.Collection.extend({
model: User
});
var userList = new UserCollection(userData);
var gridView = new GridView({
collection: userList
});
gridView.render();
$("#grid").html(gridView.el);
$('#reset').on('click',function(){
gridView.collection = new UserCollection(userData2);
gridView.render();
//$("#grid").html(gridView.el);
});