Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout CSS databinding using a function?

I have the following working code that uses Knockout to determine what color to render a state in the 2012 Presidential election. If the state value is 1 (Republican), the color is red. If the state value is 2 (Democrat), the color is blue. If the state value is 3 (Toss Up), the color is yellow.

<div class="el-clickable" data-bind="css: { 
'el-republican': model.ny()===ip.constants.electoralStatusValue.republican, 
'el-democrat': model.ny()===ip.constants.electoralStatusValue.democrat, 
'el-tossup': model.ny()===ip.constants.electoralStatusValue.tossUp 
}" 
state-abbrev="ny" style="top:26px;left:442px;height:102px;width:54px;" title="New York">
<div style="margin-top:46px;">NY</div></div>

<div class="el-clickable" data-bind="css: { 
'el-republican': model.pa()===ip.constants.electoralStatusValue.republican, 
'el-democrat': model.pa()===ip.constants.electoralStatusValue.democrat, 
'el-tossup': model.pa()===ip.constants.electoralStatusValue.tossUp 
}" 
state-abbrev="pa" style="top:107px;left:372px;height:65px;width:65px;" title="Pennsylvania">
<div style="margin-top:23px;">PA</div></div>

The problem is that this seems like such a brute force approach to the problem since I need to have 3 separate CSS binding calls in order to fetch a single CSS selector. That is, I need to check for republican, democrat and tossup for each state on my electoral college map.

(The real-world scenario is even worse as I actually check for republican, leaning republican, democrat, leaning democrat, undecided, tossup, and locked!)

http://www.ipredikt.com/contests/election2012

What I really want is a way to achieve this by calling a utility function and passing in the state value, like this:

data-bind="css: getStateColor(model.pa())" // for Pennsylvania

Is this doable with the 'attr' binding?

I've often felt that the CSS binding mechanism of: 'string-literal', true|false is very restrictive. I wish Knockout also supported something like:

data-bind="css: myFunction(myParam)"
like image 750
Armchair Bronco Avatar asked Nov 13 '22 19:11

Armchair Bronco


1 Answers

Knockout 2.2, coming out very soon (10/26/2012) will support this with the css binding. Until then, you can use this class binding to do the same thing.

like image 140
Michael Best Avatar answered Dec 19 '22 01:12

Michael Best