Knockout 3.2 amd组件没有更新observables

时间:2014-09-08 18:39:37

标签: javascript knockout.js knockout-components

我无法使用带有组件和要求的knockout 3.2来获取可观察数组。我可以手动将项目推送到视图模型中的数组中,声明没有问题,但是当它们通过ajax调用推入或通过按钮上的硬编码推送时单击DOM不会更新。

调试,我可以看到数组中有项目,但是DOM没有更新。任何帮助将不胜感激。

default.html中

<!-- ko if: state() === 'home' -->
    <template></template>
<!-- /ko -->

Template.html

<table id="items">
    <thead>
        <tr>
            <th>Category</th>
            <th>Item</th>
            <th>Cost</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Items()">
        <tr>
            <td data-bind="text: CategoryName"></td>
            <td data-bind="text: Name"></td>
            <td data-bind="text: '£' + Cost"></td>
        </tr>
    </tbody>
</table>

Startup.js

var appStateViewModel = {
    isRunning: ko.observable(false),
    state: ko.observable('home'),
    allowLog: false
};

// Configure requirejs
require.config({
    paths: {
        text: 'Scripts/text',
        knockout: '//localhost:2222/Scripts/Plugins/knockout'
    },
    urlArgs: "bust=" + (new Date()).getTime()
});

// Register knockout components
ko.components.register('template', { require: './Modules/Template/Template' });

// Apply bindings for state
var scope = document.getElementById('app');
ko.applyBindings(appStateViewModel, scope);

Template.js

define(['knockout', 'text!./Template.html'], function (ko, htmlString) {
    function TemplateViewModel(params) {

        var self = this;
        self.Items = ko.observableArray();

            $.getJSON("Items")
                .done(function (response) {

                    $.each(response, function (i, item) {
                        self.Items.push({
                            Id: item.Id,
                            Name: item.Name,
                            Description: item.Description,
                            Cost: item.Cost,
                            CategoryName: item.CategoryName
                        });
                    });
                })
                .fail(function (listResponse, status, errorThrown) {
                    alert(errorThrown);
                });
    }

    // Return component definition
    return { viewModel: TemplateViewModel, template: htmlString };
});

1 个答案:

答案 0 :(得分:1)

我找到了修复方法。看来我没有正确设置要求。

修复:

require(["knockout", "jquery", "text"], function (ko) {

    // Register knockout components
    ko.components.register('template', { require: './Modules/Template/Template' });

    // Apply bindings for state
    var scope = document.getElementById('app');
    ko.applyBindings(appStateViewModel, scope);

});