使用按钮敲除模板绑定

时间:2013-04-23 23:39:50

标签: javascript knockout.js

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

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>

没用。任何人都可以解释如何将模板绑定到按钮单击?

1 个答案:

答案 0 :(得分:2)

您可以通过向viewmodel添加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/