日々精進

新しく学んだことを書き留めていきます

knockoutでcomputedプロパティの値を変更した時の処理を書く

writeプロパティにfunctionを渡すと変更時の処理を書ける。以下の例はpureComputedだけどcomputedも同様。

this.fullName = ko.pureComputed({
    read: function () {
        return this.firstName() + " " + this.lastName();
    },
    write: function (value) {
        var lastSpacePos = value.lastIndexOf(" ");
        if (lastSpacePos > 0) { // Ignore values with no space character
            this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
            this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
        }
    },
    owner: this
});

参考:

http://knockoutjs.com/documentation/computed-writable.html