Skip to content

Instantly share code, notes, and snippets.

@oestrich
Created September 18, 2011 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oestrich/1225208 to your computer and use it in GitHub Desktop.
Save oestrich/1225208 to your computer and use it in GitHub Desktop.
Ruby DCamp - Backbone Game of Life
<!DOCTYPE html>
<html>
<head>
<title>Backbone game of life</title>
<meta charset='utf-8' />
<script type='text/javascript' src='jquery.js'> </script>
<script type='text/javascript' src='underscore.js'> </script>
<script type='text/javascript' src='backbone.js'> </script>
<style type='text/css'>
body {
background-color: #555;
}
table {
border-spacing: 0px;
padding: 0;
}
td {
height: 20px;
margin: 0;
padding: 0;
width: 20px;
}
.dead {
background-color: #000;
}
</style>
<script>
$(function() {
var Cell = Backbone.Model.extend({
initialize: function() {
this.set({alive: false});
},
cssClass: function() {
return this.get("alive") ? "" : "dead"
},
flip: function() {
var alive = this.get("alive") ? false : true;
this.set({alive: alive});
}
});
var Cells = Backbone.Collection.extend({
model: Cell
});
var CellView = Backbone.View.extend({
tagName: "td",
events: {
"click": "flip"
},
initialize: function() {
_.bindAll(this, "render");
this.model.bind("change:alive", this.render);
},
render: function() {
$(this.el).removeClass("dead");
$(this.el).addClass(this.model.cssClass());
return this;
},
flip: function() {
this.model.flip();
}
});
window.cells = new Cells();
for(i = 0; i < 25; i++) {
row = $("#board").append($("<tr></tr>")).find("tr:last");
for(j = 0; j < 25; j++) {
var cell = new Cell({x: i, y: j});
cells.add(cell);
var view = new CellView({model: cell});
row.append(view.render().el);
}
}
});
</script>
</head>
<body>
<table id="board">
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment