1

我正在学习淘汰赛,我遇到了这个例子..

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>

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

4

1 回答 1

2

您可以通过向视图模型添加一个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/

于 2013-04-23T23:50:59.047 回答