1

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

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

默认.html

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

模板.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>

启动.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);

模板.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 };
});
4

1 回答 1

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

});
于 2014-09-09T12:24:08.000 回答