Game Development Reference
In-Depth Information
Grid.prototype.addBrick = function(brick, context) {
this.bricks.push(brick);
brick.draw(context);
}
It adds the brick to its container of bricks. And after that, we just have to draw the brick onto the grid. We
don't have to trigger the big draw function in the application.js . This would be what we developers call
overkill! There is no need to clear anything because we can add the new brick on top of the grid. So all we
have to do is call the draw method of the brick.
Go ahead and try it! Open the index.html in the browser and add a few bricks to the grid. Fun, right?!
You are right! We still need to differentiate between different bricks. As you might remember, we already
implemented the buttons in the HTML markup.
<section id="bricks-container">
<form>
<button id="square-brick">Square</button>
<button id="triangle-brick">Triangle</button>
<button id="circle-brick">Circle</button>
<button id="curve-brick">Curve</button>
</form>
</section>
First we will need to make those buttons react to something. We go back to our initUI() function and add
a little more functionality.
$("#bricks-container button").click(function(event) {
event.preventDefault();
var id = $(this).attr("id");
setBrick(id);
});
We add a click callback on every button. jQuery lets us do that with only one line, thanks to the incredible
selector engine.
First we have to prevent the browser from reacting on the click with the normal behavior, such as linking to
another page. Luckily, we can stop that by using the event object that we get sent with the click. This
object offers information and functionality related with the click, such as preventDefault() . Calling this
function stops the browser from doing what it would do; so we can implement the logic of the button
ourselves.
Next, we have to find out which button was actually clicked. That is easy since the this within the click
function is a reference to the button actually clicked. With a little help from jQuery, we get the id from the
button because that lets us differentiate between the buttons easily. The id is just like every other attribute,
therefore we can read it with jQuery's attr() function.
Now we want to set the brick type that should be used from now on when clicked on the grid. We create a
function called setBrick and pass it the buttonID .
 
Search WWH ::




Custom Search