I have the simple html page, where simple ul
list defined with following viewmodel for it:
<div class="row">
<div class="col-md-6">
<button class="btn btn-link" data-bind="click: addItem">Add item</button>
<ul data-bind="foreach: listItems">
<li>
<p data-bind="text: itemText"></p>
<script>
$(document)
.ready(function() {
console.log("new li has added");
});
</script>
</li>
</ul>
</div>
<div class="col-md-6">
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</div>
</div>
<script>
function ItemViewModel(text) {
var self = this;
self.itemText = ko.observable(text || "");
}
function ListViewModel() {
var self = this;
self.listItems = ko.observableArray([]);
self.addItem = function () {
self.listItems.push(new ItemViewModel("new item: " + self.listItems().length));
};
}
ko.applyBindings(new ListViewModel());
</script>
My fiddle: https://jsfiddle.net/1c3prhhv/
Adding items to list work perfectly, though script
tag in list item template doesn't work. Each time when item adds to list, I need to execute all JavaScript
code in corresponding script
tag.
How to properly add items to Knockout's observable array with executing JavaScript
code in them?