Recently I find some of my pet projects share a common pattern, they all are based on some kind of grids. So I find myself writing similar piece of code over and over again. While re-inventing wheels is quite fun, especially when you learn new way of getting things done with every iteration, it is actually quite tedious after a while.
So after spending some time to properly plan for the grid-generation, I rewrote the grid generation, hopefully for the last time. I didn’t check whether there’s existing implementation out there though.
Not sure where I read it from, the proper way to work on the element is through event handler. Therefore I made the plugin event based-driven. Also I thought might as well made hooks for both before and after for the events (for most of them).
So long story short, before including the grid-maker script into the project, the pre-requisites are jQuery and Underscore.js (these two are probably my go-to libraries). Then initialize the grid by calling .grid()
.
$('#element').grid()
By default a responsive (buzzword alert) grid with 10 rows and 10 columns is generated. As the plugin is very much event-baseddriven, so it is possible to subscribe the events. To be precise, the before and/or after the events are fired.
For example, in order to bind a handler after the block is initialized
$('#element').grid() .trigger('board:block:init:pre', // or 'board:init:post' function(_event, context, options) { var block = this })
So in this case context
is the element that calls .grid()
, and options
is the list of options for the grid.
Getting a specific block, or a list of blocks can be done by supplying coordinates to board:block:get
and board:block:list
events respectively. Also a callback is needed so that the result can be set as the context of the callback. For example, getting a block by supplying a set of coordinates can be done as follows,
var x = 0, y = 0, callback = function() { var found_block = this } $('#element`).grid() .trigger('board:block:get', [x, y, callback])
and
var list = [[0, 0], [0, 1]], callback = function() { var found_blocks = this } $('#element`).grid() .trigger('board:block:get', [x, y, callback])
The first draft of the code is already uploaded to github for forking. I have not decide which license to use, but possibly a BSD/MIT license, or simply WTFPL. Also the detailed documentation is to be updated there instead of another announcement for endless minor changes here.