Knockout - 无法处理绑定,未定义gridViewModel

时间:2015-11-21 17:10:09

标签: javascript html knockout.js data-binding

我是淘汰赛的新手,我不知道为什么会收到这条消息。

无法处理绑定" simpleGrid:function(){return gridViewModel}" 消息:未定义gridViewModel;

library_customization.js

define(['services/logger'], function (logger) {
var title = 'Library Customization';
var vm = {
    activate: activate,
    title: title
};

return vm;


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

function activate() {
    logger.log(title + ' selected', null, title, true);
    return true;
}

});

library_customization.html

  <!DOCTYPE html>
    <html id="libraryCust">
    <head>

    <title> Project</title>

    <script type="text/javascript" src="../../Scripts/knockout-3.3.0.js
    </script>

    </head>
    <body>
    <section>
        <h2 class="page-title" data-bind="text: title"></h2>
    </section>


    <div class='liveExample'>

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

    </div>

    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

检查小提琴:JS Fiddle

我认为主要问题是您在下面的代码中提前退出模块:

var title = 'Library Customization';
var vm = {
    activate: activate,
    title: title
};

return vm;

/* your main code follows below but never executes */

所以我把这些属性移到了PagedGridModel构造函数中。