user2288976
user2288976

Reputation: 75

Knockout template binding using button

I am learning knockouts and I came across this example..

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);

I have tried making changes by adding button and would like to sort the unsorted items using that button click. Like

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

didn't work. Can anyone please explain how to bind template to button click?

Upvotes: 1

Views: 836

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You could accomplish this by adding a sort function to your viewmodel that sorts the observable array's contents, then updates the observable array with the new sorted array:

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;
};

Then you could create a button that sorts the array on click:

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

Example: http://jsfiddle.net/CCNtR/24/

Upvotes: 2

Related Questions