Created
September 18, 2011 16:02
-
-
Save oestrich/1225208 to your computer and use it in GitHub Desktop.
Ruby DCamp - Backbone Game of Life
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
<!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