I’ve got some data sent via a server, formatted like this:
[
{"Username":"user1@domain.com", "id":1},
{"Username":"user2@domain.com", "id":2},
{"Username":"user3@domain.com", "id":3}
]
I bind it to a table, but I’d like the ability to add a class to the table row when the checkbox is checked (to indicate it’s been selected). Here’s what will eventually work, and I know the problem is that Selected is not a property currently in my data.
<table>
<tbody data-bind="foreach: Items">
<tr data-bind="css:{selected: Selected}">
<td>
<input type='checkbox' data-bind="attr:{name: id}, checked: Selected" />
</td>
<td data-bind="text: Username"> </td>
</tr>
</tbody>
</table>
Since the concept of Selected is something purely for the UI, it seems a little dumb to have the server send that over the wire for each item in my data.
What I want to happen is basically this: http://jsfiddle.net/xSSMX/ but without having to add the observable Selected property on each item.
How can I add a property to each existing item in my data to achieve this?
You could just use map to add the field to the array that you get from the server like this…
Which will add Selected on to each item. Although if I’m not mistaken map isn’t supported in all browsers so you’d have to add support which you could do with a function similar to the one found here… http://www.tutorialspoint.com/javascript/array_map.htm. Or you could achieve the same effect using jQuery’s
$.each.