oop - What javascript object pattern is this example using? -
i'm making javascript/canvas game , saw example on css tricks. here's link http://css-tricks.com/9876-learn-canvas-snake-game/#comment-100804
anyways, i'm wondering because i'm refactoring game code, , creating own objects , far looks pattern using.
to me, looks revealing module pattern read on http://addyosmani.com/resources/essentialjsdesignpatterns/book/
so right?
/* note: snippet example, go link see finished example */ var js_snake = {}; js_snake.game = (function () { var ctx; js_snake.width = 200; js_snake.height = 200; js_snake.blocksize = 10; var framelength = 500; //new frame every 0.5 seconds var snake; function init() { $('body').append('<canvas id="jssnake">'); var $canvas = $('#jssnake'); $canvas.attr('width', js_snake.width); $canvas.attr('height', js_snake.height); var canvas = $canvas[0]; ctx = canvas.getcontext('2d'); snake = js_snake.snake(); bindevents(); gameloop(); } function gameloop() { ctx.clearrect(0, 0, js_snake.width, js_snake.height); snake.advance(); snake.draw(ctx); settimeout(gameloop, framelength); //do again } function bindevents() { var keystodirections = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; $(document).keydown(function (event) { var key = event.which; var direction = keystodirections[key]; if (direction) { snake.setdirection(direction); event.preventdefault(); } }); } return { init: init }; })();
also, there better pattern should using when creating objects in javascript/canvas game?
if check out game, go website. http://magnut.comze.com
the game created called fruit blitz , next update i'm working on right going big one, enemies, power ups , such.
it's instantiated function (iif) returns object 1 method. creates js_snake.game.init
method can use assigned within iif closure. i don't know if has has specific pattern name.. it's known module pattern.
see this so-question immediate function invocation
from raynos' answer i'd borrow: a lot of these "patterns" (they aren't patterns) personal preferences.
you may interested in reading more prototype pattern - base of javascript - this may start.
Comments
Post a Comment