Created
June 15, 2012 05:12
-
-
Save bialecki/2934769 to your computer and use it in GitHub Desktop.
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
<html> | |
<head> | |
<title>Backbone Views</title> | |
</head> | |
<body> | |
<table id="foobar"></table> | |
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script> | |
<script type="text/javascript" src="http://backbonejs.org/backbone-min.js"></script> | |
<script type="text/javascript"> | |
var Person = Backbone.Model.extend(); | |
var PersonCollection = Backbone.Collection.extend({ | |
model: Person | |
}); | |
var TableView = Backbone.View.extend({ | |
render: function () { | |
var self = this, | |
tableEl = $('<table><thead><tr><th>First name</th><th>Last name</th></tr></thead></table>'), | |
tbodyEl = $('<tbody />'); | |
tableEl.append(tbodyEl); | |
this.rowViews = {}; | |
this.model.get('people').each(function (model, index, collection) { | |
var rowView = new TableRowView({ | |
el: $('<tr />'), | |
model: model | |
}); | |
rowView.render(); | |
tbodyEl.append(rowView.$el); | |
self.rowViews[model.id] = rowView; | |
}); | |
this.$el.append(tableEl.children()); | |
} | |
}); | |
var TableRowView = Backbone.View.extend({ | |
events: { | |
'click td' : '_onCellClick' | |
}, | |
render: function () { | |
this.$el.data('id', this.model.id) | |
.append($('<td />').text(this.model.get('firstName'))) | |
.append($('<td />').text(this.model.get('lastName'))); | |
}, | |
_onCellClick: function (e) { | |
alert('This president is:' + this.model.get('firstName') + ' ' + this.model.get('lastName')); | |
} | |
}); | |
var tableView = new TableView({ | |
el: $('#foobar'), | |
model: new Backbone.Model({ | |
people: new PersonCollection([ | |
{ id: 1, firstName: 'Bill', lastName: 'Clinton' }, | |
{ id: 2, firstName: 'Geroge', lastName: 'Bush' }, | |
{ id: 3, firstName: 'Barack', lastName: 'Obama' } | |
]) | |
}) | |
}); | |
tableView.render(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment