0

新手,我正在努力解决这个问题。我有一个用于添加新地址的表单(为了简化它,我们只使用一个属性),更新一个数组(并将其显示在列表中),我想要实现的是能够选择其中一个地址数组并能够在表单中显示它,这可行,但是那里的更改不会更新列表中显示的内容。

视图内的代码:

<div data-bind="with: newAddress" class="span6">
    <input data-bind="value: Line1()" placeholder="Address line 1" />
    <div>
        <button data-bind="click: $parent.addAddress">Add</button>
    </div>
</div>

<div class="span4">
    <div data-bind="visible: addresses().length > 0">
        <div data-bind="foreach: addresses">
            <address>
                <span data-bind="click: $parent.removeAddress">Remove</span>
                <span data-bind="click: $parent.editAddress">Edit</span>
                <div data-bind="text: Line1"></div>                 
            </address>
        </div>
    </div>
</div>

脚本中的相关代码

function ViewModel() {
    var self = this;

    self.addresses = ko.observableArray(ko.utils.arrayMap(addresses, function(address) {
        return new Address(address);
    }));

    self.newAddress = {
        Line1: ko.observable(""),
    };

    self.addAddress = function() {
        self.addresses.push(new Address(this);
        self.newAddress.Line1("");
    };

    self.addAddress = function() {
        self.addresses.push(new Address(this);
        self.newAddress.Line1("");
    };

    self.editAddress = function() {
        self.newAddress.Line1(this.Line1);
    };

    self.remove = function() {
        self.parties.remove(this);
    };

};

// As it is used for both the addresses coming from the server and the added in
// the form I do this check
function Address(address) {
    this.Line1 = ko.isObservable(address.Line1) ? address.Line1() : address.Line1;
}

How could I achieve to bind the changes in the form when one of the addresses selected to the data displayed in the list?

谢谢

4

1 回答 1

0

该地址未更新,因为它不是可观察的。

改变这个:

function Address(address) {
    this.Line1 = ko.isObservable(address.Line1) ? address.Line1() : address.Line1;
}

对此:

function Address(address) {
    this.Line1 = ko.observable(ko.isObservable(address.Line1) ? address.Line1() : address.Line1);
}

此外,如果您不知道是否获得了可观察值,您可以使用它ko.utils.unwrapObservable来获取值,如下所示:

this.Line1 = ko.observable( ko.utils.unwrapObservable(address.Line1) );

在更仔细地查看您的代码后,我认为可以进行一些改进:

// Changed newAddress to observable with empty AdressModel
self.newAddress = ko.observable(new Address(""));

// I am assuming correct context when calling this method,
// for example clicking on a list of addressItems in the view
self.editAddress = function(addressItem) {
    self.newAddress(addressItem);
};

// The only thing the update method does is
// emptying the editor form
self.updateAddress = function () {
    self.newAddress(new Address(""));
};

// This method can only be used for adding new items,
// not updating existing items
self.addAddress = function() {
    self.addresses.push(new Address(this));
    self.newAddress(new Address(""));
};
于 2013-06-24T03:33:09.367 回答