Mark
Mark

Reputation: 14930

knockout JS bind to properties of object

I have a need to bind some HTML to an object, but my issue is that I don't know the properties of the object at development time.

I have a selectedItem property in my main view model which I have bound to a section in my HTML:

<div data-bind="with: selectedItem">

</div>

Now I want to generate a table based on the property name and property values:

<div data-bind="foreach: [WHAT DO I PUT HERE?]">
    <label class="control-label"><span data-bind="text: [OR HERE?]" /></label>
</div>

I have really no idea how to do this. Any help is greatly appreciated.

Also, just slightly extending this, I would like to handle the properties of the bound object differently, such as, if the property is just a primitive type, just output it, but if its another object/array, then handle it specially.

Can this be done?

Upvotes: 9

Views: 5729

Answers (2)

Dean North
Dean North

Reputation: 3780

If anyone else is looking to bind a simple object's properties. You can do it like this...

<table>
    <tbody data-bind="foreach: arrayOfObjects">
        <tr data-bind="foreach: Object.keys($data)">
            <td data-bind="text: $parent[$data]"></td>
        </tr>
    </tbody>
</table>

note: object.keys is not supported in older browsers, but you can use this to add backwards compatability http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation

Upvotes: 13

gbs
gbs

Reputation: 3529

Here is a working example using computed observable to select at runtime the data to show. Dynamically selected templates are also used to render the data according to the type of data to render (array or scalar).

Upvotes: 4

Related Questions