Created
November 27, 2011 20:26
-
-
Save adatta02/1398093 to your computer and use it in GitHub Desktop.
binding DOM events to objects
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
<div id="board"></div> | |
<style> | |
#board { | |
width: 150px; | |
font-size: 28px; | |
font-family: Arial; | |
margin: auto; | |
padding-top: 25px; | |
} | |
td { | |
padding: 10px; | |
} | |
</style> |
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
// Code for this blog post http://shout.setfive.com/2011/12/01/jquery-binding-dom-events-to-objects/ | |
// Live at JSFiddle - http://jsfiddle.net/fN46q/4/ | |
// JS | |
var Piece = function( board, val ) { | |
this.board = board; | |
this.val = val; | |
}; | |
var Board = function(){ }; | |
Piece.prototype = { | |
board: null, val: false, | |
render: function(){ | |
return this.val ? "X" : "O"; | |
}, | |
click: function( e ){ | |
e.data.piece.val = !e.data.piece.val; | |
e.data.piece.board.render(); | |
return false; | |
} | |
}; | |
Board.prototype = new Array(); | |
Board.prototype.render = function(){ | |
var table = $("<table></table>"); | |
for(var i=0; i < this.length; i++){ | |
var tr = $("<tr></tr>"); | |
for(var j=0; j < this[i].length; j++){ | |
var td = $("<td><a href='#'>" + this[i][j].render() + "</a></td>"); | |
$(td).find("a").bind("click", {piece: this[i][j]}, this[i][j].click); | |
td.appendTo( tr ); | |
} | |
$(tr).appendTo(table); | |
} | |
$("#board").html(""); | |
$("#board").append( table ); | |
}; | |
var gameBoard = new Board(); | |
for(var i=0; i < 3; i++){ | |
gameBoard.push( [] ); | |
for(var j=0; j < 3; j++ ){ | |
var val = ( Math.floor(Math.random() * 10) % 2 == 0 ) ? true : false; | |
var p = new Piece( gameBoard, val ); | |
gameBoard[i].push( p ); | |
} | |
} | |
gameBoard.render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment