簡體   English   中英

淘汰賽3.2 AMD組件未更新可觀察對象

[英]Knockout 3.2 amd components not updating observables

我無法使用帶有組件和要求的敲除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 };
});

我找到了解決方法。 看來我沒有正確設置要求。

解決方法:

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

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM