I’m trying to figure out why this nested template doesn’t display anything. I have 2 classes Foo/Bar, the ViewModel has an observable array of Foo, and Foo have a collection of Bar
At the moment all I see is the Foo item
ie
- someitem
instead of
-
someitem
- subitem
List item
<ul data-bind="template: {name: 'TopTemplate' , foreach: foos}"></ul>
<script type="text/html" id="TopTemplate">
<li data-bind='text: Name'>
<ul data-bind=" template: {name: 'NestedTemplate' , foreach: bars} " style="list-style-type:circle;margin-left:15px">
</ul>
</li>
</script>
<script type="text/html" id="NestedTemplate">
<li data-bind='text: Name'>
</li>
</script>
var Foo = function () {
var self = this;
self.Name = ko.observable('someitem');
self.bars = ko.observableArray([new Bar()]);
self.HasChildren = ko.observable(false);
self.addBar = function () {
self.bars.push(new Bar());
};
self.removeBar = function (param) {
self.bars.remove(param);
};
self.bars.push(new Bar());
}
var Bar = function () {
var self = this;
self.Name = ko.observable('subitem');
}
var ViewModel = function () {
var self = this;
self.foos = ko.observableArray([new Foo()]);
self.addFoo = function () {
self.foos.push(new Foo());
};
self.removeFoo = function (param) {
self.foos.remove(param);
};
}
$.ajax({
url: '@Url.Action("AddFoos")',
type: 'GET',
async: false,
contentType: 'application/json',
success: function (result) {
ko.applyBindings(new ViewModel(result));
}
});
Thanks in advance!
Knockout has an issue binding
textinli‘s for some reason. I have run into this issue before. It ends up overwriting everything else that should go on the node, which in your case is an innerul. You can fix this with aspanor any other text element like this:Here is your code in a working fiddle.
A small note, your ajax call is going to fail, since your ViewModel doesn’t have a paramater to take the result.
Also, calling
applyBindingsin a function like that is bad, since if it gets called twice you will cause errors. If you call it once, updates made to the viewmodel later will automatically get sent to the UI. That’s sort of Knockout’s thing =)Update:
Upon further consideration, this is probably not specific to
linodes. It is probably that thetextbinding works by overwriting the contents of any node it is bound to, so that any contents other than the text will also be overwritten. It is probably intentional.