編輯:我希望能夠將任何元素添加到對象中,而不僅僅是特定的年齡。如何在Knockout.js中將項添加到JSON中
有什麼方法可以將項目添加到Knockout.js中的JSON中嗎? 我想將年齡添加到下面的現有JSON中,並將其反映在網頁上。我的代碼中的點擊功能會將年齡添加到JSON中,但無法在頁面上顯示。 我也曾嘗試使用cleanNode()+ applybindings重新申請綁定,但在foreach中的項目複製
HTML:
<div data-bind="text: $data.name, visible: $data.name !== undefined" ></div>
<div data-bind="text: $data.age, visible: $data.age !== undefined" ></div>
<div data-bind="foreach: children">
<div data-bind="text: $data.name"></div>
</div>
<button id="button">Test</button>
代碼:
json = {
name: 'Scott',
children: [
{ id : 1, name : 'Alice' },
{ id : 2, name : 'Liv' }
]
}
var viewModel = ko.mapping.fromJS(json);
ko.applyBindings(viewModel, document.body);
document.getElementById("button").addEventListener("click", function() {
json.age = "87";
ko.mapping.fromJS(json, viewModel);
});
小提琴例子: https://jsfiddle.net/f8qbu1j8/6/