gpt4 book ai didi

javascript - 使用按钮进行 Knockout 模板绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 18:04:23 25 4
gpt4 key购买 nike

我正在学习 knockout ,我遇到了这个例子..

HTML/ View :

<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/ViewModel:

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>

没用。谁能解释一下如何将模板绑定(bind)到按钮点击?

最佳答案

您可以通过向您的 View 模型添加一个 sort 函数来完成此操作,该函数对可观察数组的内容进行排序,然后使用新的排序数组更新可观察数组:

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.sort = function () {
var unsorted = viewModel.instances();

viewModel.instances(unsorted.sort(viewModel.sortFunction));
};

viewModel.sortFunction = function (a, b) {
return a.FirstName().toLowerCase() > b.FirstName().toLowerCase() ? 1 : -1;
};

然后你可以创建一个按钮,在点击时对数组进行排序:

<button data-bind="click: sort">Sort</button>

示例: http://jsfiddle.net/CCNtR/24/

关于javascript - 使用按钮进行 Knockout 模板绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16180981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com