1

有以下视图模型:

Config.User = function (data) {

    var self = this;

    self.username = ko.observable();
    self.password = ko.observable();

    if (data !== undefined) {
        self.username(data.Username);
        self.password(data.Password);

    }

};

Config.Merchant = function (data) {
    var self = this;

    // Underlying data
    self.id = ko.observable();
    self.name = ko.observable();
    self.users = ko.observableArray();
    if (data !== undefined) {
        self.id(data.Id);
        self.name(data.Name);

        if (data.Users !== undefined) {
            var mappedUsers = $.map(data.Users, function (item) {
                return new Config.User(item);
            });
            self.users(mappedUsers);
        }
    }       
    });
};


Config.MerchantsViewModel = function (options) {
    var self = this;

    // Underlying data
    self.merchants = ko.observableArray();
    $.getJSON(options.loadMerchantsUrl, function (result) {
        if (result !== undefined) {
            //Set available merchants
            var mappedMerchants = $.map(result, function (item) {
                return new Config.Merchant(item);
            });
            self.merchants(mappedMerchants);
        }
    });


    self.deleteUser = function (user, merchant, viewmodel) {

            $.post(options.saveMerchantUrl, merchant, function (result) {
            if (result.success == true) {
                merchant.users.remove(user);
            }
            else {
                //TODO
            }
        });
    };
}

Html 是这样的:

<div data-bind="foreach: merchants(), visible: merchants().length > 0">
    <div>
        <label>Merchant Id :</label><input  data-bind="value: id" />
        <label>Merchant Name :</label><input  data-bind="value: name"/>
        <table>   
            <tbody data-bind="foreach: users(), visible: users().length > 0">
                <tr>
                    <td>
                        <a href="#"  data-bind="click: function(){$root.deleteUser($data, $parent.users, $root);}"><i class="icon-remove"></i></a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

一切似乎都正常工作,除了在 js 中,来自 $root.deleteUser 的 $parent.users 的 id 和 name 属性设置正确,但 users 属性是一个 0 元素的数组。此外,来自 $root.deleteUser 的 $root 将商家属性设置为 0 个元素的数组。我不太明白为什么会这样/

4

0 回答 0