Thursday, September 04, 2008

initializing js objects with many parameter

For the past couple of months I've been working on a fantasy football application on facebook. I worked primarily on the live online draft and real time fantasy scoring.

It was a lot of work and also a lot of fun. My coworkers and I spent many a night and weekend getting the site looking and working correctly. I was worried that I would get sick of thinking about football but luckily that never happened. I want to share what I learned on this project so I thought I'd start with an easy one that is now part of my personal pattern repository (ppr).

What's the best way to initialize a js object with lots of initial state? Originally, I passed in function parameters: function init(param1, param2, param3). As the complexity increased, I found myself passing in more and more parameters.

the init string was generated on the server side so my code looked like
String.format("init(%s,%s,%s,%s);", param1, param2, param3, param4).

Whenever I added a new parameter I had to change the server side code and also the js file.

After a couple of changes I wizened up and found a much better way to do things. on the server side, I created a JSONObject and set up my parameters like so:

JSONObject json = new JSONObject().put("param1", param1).put("param2", param2)....
String.format("init(%s)", json.toString())

And on the js file:

function init(params) {
var param1 = params.param1;
var param2 = params.param2;
...
}

1 comment:

Anonymous said...

hey david,

great script just in time for football season! just wondering if you've got an updated script for 2008-2009 fantasy basketball (the live scoring one) through yahoo, or if the one from last year will work the same. thanks again for what you do!

cheers,
Jay
jl4855[at]lycos[dot]com