新手知道,我正在努力解决这个问题。我有一个用于添加新地址的表单(为了简化它只允许使用一个属性),更新arrray(并将其显示在列表中),我想要实现的是能够选择其中一个数组中的地址,并能够在表单中显示它,这是有效的,但那里的更改不会更新列表中显示的。
视图中的代码:
<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;
}
如果选择其中一个地址到列表中显示的数据,我怎样才能实现绑定表单中的更改?
由于
答案 0 :(得分: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(""));
};