我正在尝试绑定一个在内部使用可观察数组的计算observable。 加载时会调用“read”方法。 但是,当表中的值发生更改并移动焦点时,不会调用“write”方法。 请注意,对于不包装数组而是简单字符串的简单计算的observable,“write”方法有效。但是对于这种情况,它不起作用。 我查看了Knockout api文档和在线论坛,但找不到任何相关信息。有人可以请教吗? 以下是HTML代码
<thead>
<tr><th>People Upper Case Name</th></tr>
</thead>
<tbody data-bind="foreach: uppercasepeople">
<tr>
<td ><input type="text" data-bind="value: name"/></td>
</tr>
</tbody>
</table>
以下是Java脚本代码
<script type="text/javascript">
var MyViewModel = function () {
var self = this;
var self = this;
//Original observable array is in lower case
self.lowercasepeople = ko.observableArray([
{ name: "bert" },
{ name: "charles" },
{ name: "denise" }
]);
//coputed array is upper case which is data-bound to the ui
this.uppercasepeople = ko.computed({
read: function () {
alert('read does get called :)...yaaaa!!!');
return self.lowercasepeople().map(function (element) {
var o = { name: element.name.toUpperCase() };
return o;
});
},
write: function (value) {
alert('Write does not get called :(... why?????');
//do something with the value
self.lowercasepeople(value.map(function (element) { return element.toLowerCase(); }));
},
owner: self
});
}
ko.applyBindings(new MyViewModel());
我已将代码与Knockout API文档中显示的示例类似,以便人们轻松关联。
答案 0 :(得分:0)
计算出的observable,你只处理数组本身。只有在您尝试直接设置write
的值时才会调用uppercasepeople
函数。
在这种情况下,您可能希望在person对象本身上使用可写的可计算方法,并使名称可观察。可编写的计算机然后将名称转换为大写,并且在写入时将使用小写值填充名称observable。
答案 1 :(得分:0)
var MyViewModel = function () {
var self = this;
//Original observable array is in lower case
self.lowercasepeople = ko.observableArray([
{ name: "bert" },
{ name: "charles" },
{ name: "denise" }
]);
self.recententlyChangedValue = ko.observable();
//coputed array is upper case which is data-bound to the ui
this.uppercasepeople = ko.computed({
read: function () {
alert('read does get called :)...yaaaa!!!');
return self.lowercasepeople().map(function (element) {
var o = { name: element.name.toUpperCase() };
return o;
});
},
write: function (value) {
alert('It will be called only when you change the value of uppercasepeople field');
//do something with the value
self.recententlyChangedValue(value);
},
owner: self
});
}