Note that there are some explanatory texts on larger screens.

plurals
  1. POKnockout.js nested model and observable arrays
    text
    copied!<p>I'm new to Knockout and have some problems at the beginning. Consider following model:</p> <pre><code>// @param {String} content Content of the post // @param {number} reply_to ID indicating to which post this post is replying // @param {Array} replies Array of DiscussionPosts indicating replies to this post var DiscussionPost(content, reply_to, replies) { var self = this; self.content = content; self.reply_to = reply_to; self.replies = ko.observableArray( ko.utils.arrayMap(replies, function(reply) { return new DiscussionPost(reply.content, reply.reply_to, reply.replies); }) } </code></pre> <p>Now for my view model, consider I have all my posts in a flat array called <code>allPosts</code> and try to build a structure with previous model as follows:</p> <pre><code>var rootPosts = allPosts.filter(function (o) { return o.reply_to === null; }); var result = (function iterate(posts) { var tree = []; $.each(posts, function(i, post){ var replies = allPosts.filter(function(o) { return o.reply_to === post.id; }); if (replies.length &gt; 0) { replies = iterate(replies); } var tmpPost = new DiscussionPost(post.content, post.reply_to, replies); tree.push(tmpPost); }); return tree; })(rootPosts); </code></pre> <p>Theoretically, the <code>result</code> variable shall contain graph of all posts with those posts that don't have any parent at root. For instance for the following tree it shall return an array with one element i.e.the root, then its replies should be C1 and C2 and array for replies of C1 shall contain only C3. Problem is that root is filled as expected, and its replies are C1 and C2, but replies of C1 returns an array with four elements of type DiscussionPost which all properties (content, reply_to, and replies) are undefined. If instead of Knockouts' observable array I use regular javascript array in my model everything works fine even at 100 level deep. </p> <pre><code> root / \ / \ C1 C2 / C3 </code></pre>
 

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