Skip to content

Instantly share code, notes, and snippets.

@smith
Created December 15, 2011 15:48
Show Gist options
  • Save smith/1481573 to your computer and use it in GitHub Desktop.
Save smith/1481573 to your computer and use it in GitHub Desktop.
Things I Like About Iowa - The Demo
<!doctype html>
<html>
<head>
<title>A Demo: Things I Like About Iowa</title>
</head>
<body>
<h1>Things I Like About Iowa</h1>
<a href="#">home</a>
<div id="container"></div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
<script>
// # Things I Like About Iowa
//
// Nathan L Smith <nlloyds@gmail.com>
//
// A contrived demo app to show off some capabilities of Backbone.js
// (http://documentcloud.github.com/backbone/)
//
// For presentation at the December 2011 IowaJS meeting.
//
// Public Domain License.
(function () {
var router, el = $("#container"), items = [], listView;
// Model
var Thing = Backbone.Model.extend({});
// Collection
var List = Backbone.Collection.extend({
model: Thing
});
// Views
var ListItemView = Backbone.View.extend({
tagName: "li",
events: {
"click a": "showThing"
},
render: function () {
var id = this.model.attributes.id;
$(this.el).html($("<a />").attr({ href: id }).html(id));
return this;
},
showThing: function () {
router.navigate("things/" + this.model.attributes.id, true);
return false;
}
});
var ListView = Backbone.View.extend({
el: el,
render: function () {
$(this.el).html($("<ul />").append(this.collection.map(function (item) {
return new ListItemView({ model: item }).render().el;
})));
return this;
}
});
var ThingView = Backbone.View.extend({
el: el,
render: function () {
$(this.el).html(this.model.attributes.action);
return this;
}
});
// Router
var Router = Backbone.Router.extend({
routes: {
"": "home",
"things/:thing": "showThing"
},
home: function () {
listView = (listView || new ListView({ collection: items })).render();
},
showThing: function (id) {
(new ThingView({ model: items.get(id) })).render();
}
});
router = new Router;
// Startup
items = new List([
{ id: "Guns", action: "Bang!" },
{ id: "Casserole", action: "Yum tots!" },
{ id: "Jesus", action: "Hallelulah!" },
{ id: "Meth", action: "Let's not sleep!" },
{ id: "Dogs", action: "Get 'em boy!" }
]);
Backbone.history.start();
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment