19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Knockout.js ObservableArray を部分的に更新

Last updated at Posted at 2014-09-05

数時間ハマったのでメモ。
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 を使用。

19
20
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?