Here is functional code that uses Knockout to decide which color to use when rendering a state in the 2012 Presidential election. If the state value is 1 (Republican), it will be displayed in red. If the state value is 2 (Democrat), it will be displayed in blue. If the state value is 3 (Toss Up), it will be displayed in 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 issue with this approach is that it seems like a brute force method because I need to make 3 separate CSS binding calls just to retrieve one CSS selector. This means I have to check for republican, democrat, and tossup for each state on my electoral college map.
(In reality, it's even more complicated as I also check for leaning republican, leaning democrat, undecided, tossup, and locked states!)
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 there a way to accomplish this using the 'attr' binding?
I have often thought that the CSS binding mechanism of: 'string-literal', true|false is very limiting. I wish Knockout also supported something like:
data-bind="css: myFunction(myParam)"