2

我正在尝试绑定一个内部使用可观察数组的计算可观察对象。加载时确实会调用“读取”方法。但是当表中的值改变并且焦点被移动时,不会调用“write”方法。请注意,对于不包装数组而是简单字符串的简单计算 observables,“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 代码

    <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 文档中显示的示例类似,以便人们轻松关联。

4

2 回答 2

0

您拥有的计算出的 observable 只处理数组本身。write仅当您尝试直接设置 的值时,才会调用该函数uppercasepeople

在这种情况下,您可能希望使用在 person 对象本身上计算的可写对象并使名称可观察。然后,可写计算将名称转换为大写,并在写入时用小写值填充可观察的名称。

于 2013-02-17T03:49:35.060 回答
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
});
}
于 2013-02-18T07:03:22.303 回答