Knockout JS and recursive pattern

I saw this question , and its method causes an error on the JS Uncaught SyntaxError: Unexpected token ) console Uncaught SyntaxError: Unexpected token ) .

I am trying to take a recursive array of categories that have the Children property, which is an array of categories, and create them using the jquery template. Every method I tried leads to some syntax error. I checked that the object displayed correctly in javascript (it comes from MVC3 using @Html.Raw(Json.Encode(Model.Categories)) to get it into a JS array). Here is the original csharp class

 public class CategoryTreeModel { public int Id { get; set; } public string Name{ get; set; } public bool Selected { get; set; } public bool HasChildren { get { return Children.Count > 0; } } public List<CategoryTreeModel> Children { get; set; } } 

This is the original html that invokes the first level of the template:

 <ul class="nav" data-bind="template: {name: 'categories_template', foreach: categories}"> </ul> 

and the template itself:

 <script type="text/html" id="categories_template"> <li id="category_${Id}" class="category_header">${Name} {{if $data.HasChildren }} <ul data-bind='template: { name: "categories_template", foreach: Children}'> </ul> {/if} </li> 

The template works if I take it out to the child, doing the first level correctly. I get Uncaught SyntaxError: Unexpected token ) when I use the code as is. What am I doing wrong?

+7
source share
2 answers

Your last {/if} should be {{/if}}

Here is an example: http://jsfiddle.net/rniemeyer/vbKVC/

+4
source

I think I have a slightly better solution. Please see:

http://jsfiddle.net/nonsense66/Bzekr/

Template:

 <script id="treeElement" type="text/html"> <li> <span data-bind="text: name"></span> <ul data-bind="template: { name: 'treeElement', foreach: children }"> </ul> </li> </script> <ul data-bind="template: { name: 'treeElement', foreach: $data.treeRoot }"></ul> 

JavaScript:

 var viewModel = { treeRoot: ko.observableArray() }; var TreeElement = function(name, children) { var self = this; self.children = ko.observableArray(children); self.name = ko.observable(name); } var tree = [ new TreeElement("Russia", [ new TreeElement("Moscow") ]), new TreeElement("United States", [ new TreeElement("New York", [ new TreeElement("Harlem"), new TreeElement("Central Park") ]) ]) ]; viewModel.treeRoot(tree); ko.applyBindings(viewModel); 

Hope this helps

+1
source

All Articles