zoukankan      html  css  js  c++  java
  • Knockout Grid

    http://wijmo.com/grid-with-knockout-viewmodel-loading-remote-data/

    We were hearing quite a few people asking how to best create a knockout ViewModel for our Grid with data fetched from a remote service. In order to help guide people through this scenario, we sat down and built an implementation. Along the way we added some features (as of Wijmo 2.2.0) to the Grid to make this even easier. Follow along to build your own Grid ViewModel using knockout. You can also see the knockout Grid demo online.

    Add JavaScript & CSS Dependencies

    Add the following dependencies to your page: jQuery, jQuery UI, Wijmo & Knockout.

    <!-- jQuery -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>
    <!-- Wijmo CSS and script -->
    <link type="text/css" href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" />
    <link type="text/css" href="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.2.0.min.css" rel="stylesheet" />
    <script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-open.all.2.2.0.min.js"></script>
    <script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.2.0.min.js"></script>
    <!-- KnockoutJS for MVVM-->
    <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout-2.1.0.js"></script>
    <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout.wijmo.js"></script>

    Create the ViewModel

    Now we need to create the ViewModel for our Grid. This is where all the magic is. Our ViewModel is tailored to the Grid and has properties that the Grid will bind to for its options. The load method will be called from outside the ViewModel when new data is needed from the server. This web service happens to be an OData service, but any service type can be used here.

    //Create ViewModel
    var viewModel = {
        pageSize: ko.observable(10),
        pageIndex: ko.observable(0),
        sortCommand: ko.observable("ProductID asc"),
        dataRows: ko.observableArray([]),
        totalRows: ko.observable(0),
        sorted: function (e, data) {
            viewModel.sortCommand(data.sortCommand);
        },
        paged: function (e, data) {
            viewModel.pageIndex(data.newPageIndex);
        },
        load: function () {
            $.ajax({
                url: "http://services.odata.org/Northwind/Northwind.svc/Products",
                dataType: "jsonp",
                jsonp: "$callback",
                data: {
                    $format: "json",
                    $inlinecount: "allpages",
                    $select: "ProductID,ProductName,UnitPrice,UnitsInStock",
                    $orderby: viewModel.sortCommand(),
                    $top: viewModel.pageSize(),
                    $skip: viewModel.pageIndex() * viewModel.pageSize(),
                    "paging[pageIndex]": viewModel.pageIndex(),
                    "paging[pageSize]": viewModel.pageSize()
                },
                success: function (result) {
                    var data = result.d.results;
                    var arr = [];
    
                    $.each(data, function (i) {
                        arr.push(new product(data[i]));
                    });
                    viewModel.totalRows(result.d.__count);
                    viewModel.dataRows(arr);
                }
            });
        }
    
    };
    
    //Class constructor for grid row. Returns observable properties.
    var product = function (data) {
        return {
            ProductID: ko.observable(data.ProductID),
            ProductName: ko.observable(data.ProductName),
            UnitPrice: ko.observable(data.UnitPrice),
            UnitsInStock: ko.observable(data.UnitsInStock)
        };
    };

    Create the View

    This markup is really simple. We are just adding a Wijmo Dropdown (select) and Grid (table) to the page and binding their options to the ViewModel.

    <div class="toolbar">
    <label>Display: </label>
    <select data-bind="value: pageSize, wijdropdown: {}">
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="20">20</option>
    </select>
    </div>
    <table id="dataGrid" data-bind="
    wijgrid: {
    data: dataRows,
    pageSize: pageSize,
    pageIndex: pageIndex,
    totalRows: totalRows,
    allowPaging: true,
    allowSorting: true,
    sorted: sorted,
    pageIndexChanged: paged,
    columns: [
    { sortDirection: 'ascending', dataType: 'number', dataFormatString: 'n0', headerText: 'ID',  60 },
    { headerText: 'Product' },
    { dataType: 'currency', headerText: 'Price',  100},
    { dataType: 'number', dataFormatString: 'n0', headerText: 'Units',  100}]
    }">
    </table>

    Initializing the App

    Now the we have a ViewModel and View, we can initialize the app. This code initializes the KO bindings and adds listeners for critical components of the ViewModel in order to call the load() method when new data is needed.

    //Bind ViewModel and Event Handlers
    $(document).ready(function () {
        ko.applyBindings(viewModel);
        viewModel.load();
        viewModel.sortCommand.subscribe(function (newValue) {
            viewModel.load();
        });
        viewModel.pageIndex.subscribe(function (newValue) {
            viewModel.load();
        });
        viewModel.pageSize.subscribe(function (newValue) {
            viewModel.load();
            $(":wijmo-wijdropdown").wijdropdown("refresh");
        });
    });

    Run It!

    That's it, just run your app and you have a Grid that fetches remote data when paging and sorting. You could also add other widgets to the app and bind to the same data in the ViewModel. This is the ideal solution for using knockout and the Wijmo Grid.

    This demo is included in the download under Wijmo-Complete/development-bundle/demo-apps/knockout-grid. You can also play with the live version of this knockout Grid demo online.

  • 相关阅读:
    javascript回调函数笔记
    JavaScript回调函数的实现
    深入理解JS执行细节(写的很精辟)
    javascript中return function与return function()的区别
    windows下dubbo-admin2.6.x之后版本的安装
    shiro经典通俗易懂javase例子
    字符串转数字练习--String to Integer (atoi)
    字符串按照Z旋转90度然后上下翻转的字形按行输出字符串--ZigZag Conversion
    SQL ----post漏洞测试注入
    nginx笔记----解决windows80端口被iis占用
  • 原文地址:https://www.cnblogs.com/zkwarrior/p/4801091.html
Copyright © 2011-2022 走看看