【发布时间】:2016-03-11 00:38:34
【问题描述】:
我是 Knockoutjs 的初学者。在使用集合时,在我看来绑定不起作用(显示文本,但在值更新后未更新)。例如以下代码:
<h2>People</h2>
<ul data-bind="foreach: people">
<li>
<div>
<span data-bind="text: name"> </span> has <span data-bind='text: children().length'> </span> children:
<a href='#' data-bind='click: addChild '>Add child</a>
<span class='renderTime' data-bind='visible: $root.showRenderTimes'>
(person rendered at <span data-bind='text: new Date().getSeconds()' > </span>)
</span>
</div>
<ul data-bind="foreach: children">
<li>
<input type="text" data-bind="value: $data">
<span data-bind="text: $data"> </span>
<span class='renderTime' data-bind='visible: $root.showRenderTimes'>
(child rendered at <span data-bind='text: new Date().getSeconds()' > </span>)
</span>
</li>
</ul>
</li>
</ul>
<label><input data-bind='checked: showRenderTimes' type='checkbox' /> Show render times</label>
这是官方 Knockout.js 网站上的示例代码 http://knockoutjs.com/examples/collections.html 源js代码是这样的:
// Define a "Person" class that tracks its own name and children, and has a method to add a new child
var Person = function(name, children) {
this.name = name;
this.children = ko.observableArray(children);
this.addChild = function() {
this.children.push("New child");
}.bind(this);
}
// The view model is an abstract description of the state of the UI, but without any knowledge of the UI technology (HTML)
var viewModel = {
people: [
new Person("Annabelle", ["Arnie", "Anders", "Apple"]),
new Person("Bertie", ["Boutros-Boutros", "Brianna", "Barbie", "Bee-bop"]),
new Person("Charles", ["Cayenne", "Cleopatra"])
],
showRenderTimes: ko.observable(false)
};
ko.applyBindings(viewModel);
我刚刚进行了一项更改 - 添加了
<input type="text" data-bind="value: $data">
一切都很好显示。但是值更改后文本不会更新。似乎绑定不起作用。我在实际项目中也遇到了同样的问题。这让我很困惑。怎么了? 提前致谢。
【问题讨论】:
标签: knockout.js binding