0

我正在使用 Knockout.js、require.js 等开发 MVVM Web 应用程序。问题是我无法访问视图模型中属性(可观察数组类型)中的项目。

样本合同模型:

define('model.contract', ['ko'],
    function (ko) {
        var Contract = function () {
            var self = this;
            self.id = ko.observable();
            self.subject = ko.observable().extend({ required: true });

            self.shoppingItems = ko.observableArray();

           };
           return Contract;
    });

示例视图模型:

define('vm.contract', ['ko'],
    function (ko) {
        var contract = ko.observable(), // Is initialised as viewmodel activates

            deleteCmd = function () {

                var selectedId = getSelectedId(),
                    deletedId = contract.shoppingItems.remove(function (item) { return item.id === selectedId; });

                alert('Item ' + deletedId[0].id + ' was deleted!');
            };

        return {
            contract: contract,
            deleteCmd: deleteCmd
        };
    });

示例视图:

<div data-bind="template: {name: shoppingItemTemplate, foreach: contract().shoppingItems}"></div>
<button data-bind="click: deleteCmd">Delete Selected</button>

我需要在 viewmodel 中访问的是contract.shoppingItems,我得到的只是未定义的。

4

1 回答 1

0

为什么你定义你的contractasobservableArray而不是 just observable

也不要忘记你应该调用contract()来获取contractobservable 的值:

// ...
deletedId = contract().shoppingItems.remove(function (item) { return item.id === selectedId; });
// ...

更新:刚刚注意到你不正确地定义了model.contract. 将您的return Contract外部Contract定义块:)

define('model.contract', ['ko'],
    function (ko) {
        var Contract = function () {
            var self = this;
            self.id = ko.observable();
            self.subject = ko.observable().extend({ required: true });

            self.shoppingItems = ko.observableArray();
         };

        return Contract;
    }
);
于 2013-03-16T10:23:04.363 回答