Help us understand the problem. What is going on with this article?

Knockout.js ObservableArray を部分的に更新

More than 5 years have passed since last update.

数時間ハマったのでメモ。
observableArray で複雑なオブジェクトを含む配列を渡した時、
オブジェクトのプロパティを部分的に更新する。

html
<!-- ko foreach: myItems -->
    <li>アイテム <span data-bind="text: $data.value"></span></li>
<!-- /ko -->
javascript
var items = [
        {value: 'a'},
        {value: 'b'},
        {value: 'c'}
    ];

var bindObj = {
        myItems: ko.observableArray(items)
    };

ko.applyBindings(bindObj);

var ob = bindObj.myItems;
var idx = 1;

// 新しいオブジェクトだと更新される
// ob.splice(idx, 1, {value: 'b updated'});

var b = items[idx];

b.value = 'b updated';

// 同じオブジェクトだと更新されない
// ob.splice(idx, 1, b);

// しかたないからディープコピー
ob.splice(idx, 1, $.extend(true, {}, b));

同じオブジェクトのプロパティを書き換えて splice しても、値が更新されなかった。
しかたないので、ディープコピーしてから更新。
コピーには今回 jQuery.extend を使用。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away