我正在学习淘汰赛,我遇到了这个例子..
HTML/视图:
<h2>Not sorted</h2>
<ul data-bind="template: { name: 'instanceTmpl', foreach: instances }"></ul>
<hr/>
<h2>Sorted</h2>
<ul data-bind="template: { name: 'instanceTmpl', foreach: sortedInstances }"></ul>
<script id="instanceTmpl" type="text/html">
<li>
<span data-bind="text: id"></span>
<input data-bind="value: FirstName" />
</li>
</script>
JavaScript/视图模型:
function Instance(id, name) {
return {
id: ko.observable(id),
FirstName: ko.observable(name)
};
}
var viewModel = {
instances: ko.observableArray([
new Instance(1, "Zed"),
new Instance(2, "Jane"),
new Instance(3, "John"),
new Instance(4, "Anne"),
new Instance(5, "Ted")
])
};
viewModel.sortFunction = function (a, b) {
return a.FirstName().toLowerCase() > b.FirstName().toLowerCase() ? 1 : -1;
};
viewModel.sortedInstances = ko.dependentObservable(function () {
return this.instances.slice().sort(this.sortFunction);
}, viewModel);
ko.applyBindings(viewModel);
我尝试通过添加按钮进行更改,并希望使用该按钮单击对未排序的项目进行排序。喜欢
<button data-bind="click: sortedInstances">Sort</button>
没用。谁能解释一下如何将模板绑定到按钮点击?