1

我有绑定到 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 上进行修改时,它不会被考虑。

其中一种方法是将普通数组放入可观察对象中。

是否有任何代码示例来说明这一点或任何更好的方法?

请帮忙。

4

2 回答 2

0

我认为使您的可观察数组对象的属性充当可观察的最佳方法是使它们也可观察,以便您创建包含也可观察的可观察数组。例如::

    var viewModel = {
    accounts: ko.observableArray([]),
    init: function () {
        this.accounts.push({
            Property1: ko.observable("some value"),
            Property2: ko.observable("some value"),
            Property3: ko.observable("some value")
            });
        }
    };

请检查这个问题,我认为这就是你要找的

可观察数组内的对象更新已完成,但浏览器未发生更改

于 2013-04-01T12:01:45.370 回答
0
function MyObject(val1, val2)
{
   this.firstProperty = ko.observable(val1);  
   this.secondProperty = ko.observable(val1);
}  

var myViewModel = new function()  
{  
   var self = this;
   self.values = ko.observableArray([]);  
   self.values.push(new MyObject("value11", "value12"));  
   self.values.push(new MyObject("value21", "value22"));
}
于 2013-04-01T12:06:54.267 回答