December 20th, 2008
Here’s a technique you can use to DRY (Don’t repeat yourself) up your code, if you have very similiar methods that just do the “opposite”.
An example of this are controls that do scrolling or paging, and often include a forward/back button.
I often see code like this:
The “do something” part in methods like these is almost identical, except for the direction. Basically, it all resolves around incrementing or decrementing a “position” variable, checking bounds, and then rendering the result.
I find it more convenient to merge this into one function, with a direction parameter, that gets +1 or -1. Here’s an example:
var currentPage = 1, pageCount = 10; |
(currentPage == 0) ? pageCount : |
(currentPage == pageCount+1) ? 1 : currentPage; |
Of course it’s not nice to write
everytime you want to page to the previous page, so here’s where Prototype comes to the rescue (and yes, I’m pimping Prototype here):
var nextPage = turnPage.curry(1), |
previousPage = turnPage.curry(-1); |
With curry, you get instant next and previous functions, which you can call like any ol’ function:
$( 'previous_button' ).observe( 'click' ,previousPage); |
How sweet is that!