Note that there are some explanatory texts on larger screens.

plurals
  1. POKnockout.js Make every nested object an Observable
    primarykey
    data
    text
    <p>I am using Knockout.js as a MVVM library to bind my data to some pages. I'm currently building a library to make REST calls to a web service. My RESTful web service returns a simple structure:</p> <pre><code>{ id : 1, details: { name: "Johnny", surname: "Boy" } } </code></pre> <p>I have an observable main parent, <code>myObject</code>. When I do</p> <pre><code>myObject(ko.mapping.fromJS(data)) </code></pre> <p>the observables in <code>myObject</code> are:</p> <ul> <li><code>id</code></li> <li><code>name</code></li> <li><code>surname</code></li> </ul> <p>How can I make <code>details</code> (and theoretically any object in the structure an observable)? I need this behavior so that i can set a computed observable on details and get noticed as soon as any of the internal data changes.</p> <p>I have set up a basic recursive function which should do the trick. It doesn't, of course, <code>myObject.details</code> doesn't become an observable.</p> <pre><code>// Makes every object in the tree an observable. var makeAllObservables = function () { makeChildrenObservables(myObject); }; var makeChildrenObservables = function (object) { // Make the parent an observable if it's not already if (!ko.isObservable(object)) { if ($.isArray(object)) object = ko.observableArray(object); else object = ko.observable(object); } // Loop through its children for (var child in object()) { makeChildrenObservables(object()[child]); } }; </code></pre> <p>I'm pretty sure it's something about incorrect references, but how can I solve this? Thank you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload