我正在使用 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
,我得到的只是未定义的。