Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js - Adding properties to data sent serverside

I've got some data sent via a server, formatted like this:

[
  {"Username":"[email protected]", "id":1},
  {"Username":"[email protected]", "id":2},
  {"Username":"[email protected]", "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?

like image 939
FiniteLooper Avatar asked Aug 21 '26 04:08

FiniteLooper


1 Answers

You could just use map to add the field to the array that you get from the server like this...

data = data.map(function(item) {
            item.Selected = ko.observable(false);
            return item;
        });

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.

like image 138
MHollis Avatar answered Aug 23 '26 18:08

MHollis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!