我有绑定到 UI 上的 html 字段的可观察数组。
但是,UI 上这些字段的更改不会反映在视图模型中,因为根据 Knockout 文档,可观察数组跟踪数组中的对象,而不是这些对象的状态。
代码如下所示:
var RewardMissionModel = function () {
var self = this;
self.achievementID = ko.observable();
self.rewardAsset = ko.observable();
self.rewards = ko.observableArray([new Reward("Points", "Qty", "", "Item", "")]);
self.isDirty = false;
//Add reward
self.addReward = function () {
//var self = this;
var tempRewardType = "Points";
self.rewards.push(new Reward(tempRewardType, "Qty", "", "Item", "", 0));
};
//Remove reward
self.removeReward = function (reward) {
if (self.rewards().length > 1)
self.rewards.remove(reward);
};
//------------------------------------------------------------------------------
};
function Reward(rewardType, quantityLabel, rewardQuantity, itemLabel, item, itemID) {
var self = this;
//self.viewModel = viewModel;
self.rewardTypes = ["Points", "Coins", "Items"];
self.rewardType = ko.observable(rewardType);
self.itemLabel = ko.observable(itemLabel);
self.itemText = ko.observable(item);
self.quantityLabel = ko.observable(quantityLabel);
self.rewardQuantity = ko.observable(rewardQuantity);
this.selectedRewardType = ko.observable(rewardType);
self.isItemType = function (selectedRewardType) {
return selectedRewardType === this.selectedRewardType();
}
self.itemID = ko.observable(itemID);
}
HTML 代码:
<div data-bind="template: { name: 'rewards-template', foreach: rewards }"></div>
<script type="text/html" id="rewards-template">
<span style="margin-left:30px">Reward Type</span>
<select class="dropdown" data-bind="options: rewardTypes, value: selectedRewardType"></select>
<span data-bind="text: itemLabel, visible: isItemType('Items')"></span>
当我将对象添加或删除到可观察数组中时,会设置 viewmodel 脏标志,但是当我在 UI 上进行修改时,它不会被考虑。
其中一种方法是将普通数组放入可观察对象中。
是否有任何代码示例来说明这一点或任何更好的方法?
请帮忙。