Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
Mark Avatar asked Oct 02 '12 07:10

Mark


1 Answers

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

like image 183
Dean North Avatar answered Sep 20 '22 13:09

Dean North