Introductory examples

Detailed examples

Paged grid

The data-bind="..." bindings like text, visible, and click are not fixed - you can easily add custom ones. If your custom binding merely adds event handlers or updates properties of a DOM element, you can implement it in just a few lines.

However, you can also use custom bindings as a way to create reusable components (or plugins) such as the simpleGrid binding demonstrated on this page.

If a plugin provides its own standard view model class (e.g., ko.simpleGrid.viewModel in this example), this provides both a way to configure how an instance of the plugin should work (in this example: page size, column definitions) and if properties on the view model are observable (in this example: current page index), it also makes it easy for external code to write to those properties and cause the UI to be updated. For example, see how the “Jump to first page” button works.

Take a look at the HTML source code - it’s pretty easy to use and interact with this simple grid.

Live example

Source code: View

 
<div data-bind='simpleGrid: gridViewModel'> </div>

<button data-bind='click: addItem'>
    Add item
</button>

<button data-bind='click: sortByName'>
    Sort by name
</button>

<button data-bind='click: jumpToFirstPage, enable: gridViewModel.currentPageIndex'>
    Jump to first page
</button> 

Source code: View model

    var initialData = [
        { name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
        { name: "Speedy Coyote", sales: 89, price: 190.00 },
        { name: "Furious Lizard", sales: 152, price: 25.00 },
        { name: "Indifferent Monkey", sales: 1, price: 99.95 },
        { name: "Brooding Dragon", sales: 0, price: 6350 },
        { name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
        { name: "Optimistic Snail", sales: 420, price: 1.50 }
    ];

    var PagedGridModel = function(items) {
        this.items = ko.observableArray(items);

        this.addItem = function() {
            this.items.push({ name: "New item", sales: 0, price: 100 });
        };

        this.sortByName = function() {
            this.items.sort(function(a, b) {
                return a.name < b.name ? -1 : 1;
            });
        };

        this.jumpToFirstPage = function() {
            this.gridViewModel.currentPageIndex(0);
        };

        this.gridViewModel = new ko.simpleGrid.viewModel({
            data: this.items,
            columns: [
                { headerText: "Item Name", rowText: "name" },
                { headerText: "Sales Count", rowText: "sales" },
                { headerText: "Price", rowText: function (item) { return "$" + item.price.toFixed(2) } }
            ],
            pageSize: 4
        });
    };

    ko.applyBindings(new PagedGridModel(initialData));

Try it in jsFiddle