我有以下标记:
<ul data-bind="foreach: nameList">
<li data-bind="text: $data"></li>
</ul>
<button data-bind="click: addname">add name</button>
Total names: <span data-bind="text: nameList().length"></span>
我的 View 模型如下所示:
var viewmodel = {
nameList: ko.observableArray(["Brian"]),
number: ko.observable(100),
addname: function(){
alert(this.nameList().length);
this.nameList().push("name");
alert(this.nameList().length);
}
};
ko.applyBindings(viewmodel);
每当执行addname方法时,alert都会更新nameList数组,但是 标记不反射(reflect)这些更改。那么这有什么问题吗?
最佳答案
明白了!您需要更改:
this.nameList().push("name");
对此:
this.nameList.push("name");
(因为nameList
是一个数组,而不是一个方法)
关于javascript - knockout 不更新 View 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15689913/