4

我有一个奇怪的问题,至少我觉得很奇怪。

以下将不显示任何内容:

<input type="text" data-bind="value: selectedAddress.street1" />

但是,如果像这样绑定,那么它会显示正确的值,但不会更新(显示值但似乎没有绑定到对象):

<input type="text" data-bind="value: ko.toJS($data).selectedAddress.street1" />

我检查了 selectedAddress 对象是否实际上包含以下数据:

JSON.stringify(ko.toJS(selectedAddress), null, 2)

它确实

{
 "id": 5631,
 "street1": "Some Adress 43",
 "street2": null,
 "postcode": "15850",
 "city": "GhostTown",
 "country": "UK",
 "addressTypes": []
}

如何让输入字段正确绑定到对象属性并相应地显示/更新值?

视图模型:

var theViewModel = function() {
        var self = this;
        self.no = ko.observable();
        self.name = ko.observable();
        self.addresses = ko.observableArray([]);
        self.selectedAddress = ko.observable(new Address());
        ...
}

我究竟做错了什么?

4

3 回答 3

3

括号仅在某些情况下是可选的,但在引用对象的属性(可能是也可能不是 observable 的值)时不是。因此,您需要显式使用括号来获取 observable 的值selectedAddress。然后,你可以参考street1这个对象的属性(括号现在是可选的):

data-bind="value: selectedAddress().street1"
于 2012-06-09T23:36:28.440 回答
2

这是单向绑定的解决方案(值不会更新)。

这是来自 KnockoutJS 文档http://knockoutjs.com/documentation/value-binding.html的引用

如果您引用的不是简单属性,例如复杂的 JavaScript 表达式或子属性,KO 会将表单元素的初始状态设置为该值,但当用户编辑时,它将无法写回任何更改表单元素。在这种情况下,它是一次性的值设置器,而不是真正的绑定。

要获得双向绑定功能,请使用模板。就像是:

<script type="text/html" id="someTemplate">
    <input type="text" data-bind="value: street1" />
</script>

<div data-bind="template: { name: 'someTemplate', data: selectedAddress }"></div>
于 2012-07-07T12:35:08.787 回答
0

If someone had the same issue and wondered about this part

self.selectedAddress = ko.observable(new Address());

And you might ask whether there's a need to create a constructor or an object to fill up the ko.observable function, well you can, but if you don't like creating a model for this one, just add up an empty array and the parenthesis method should work.

example :

self.selectedAddress = ko.observable([]);

then :

selectedAddres().street1

This may not work for other instances but so far it worked on me. Thank you for this answer too, saved me a lot of time!

于 2018-01-15T04:44:58.727 回答