0
0

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.

Backboneで配列の変更にあわせて通知を送る。

Last updated at Posted at 2015-03-24

Backboneで配列をsetすると配列を連想配列に変換するという挙動をする。
consoleで軽く試す。

var a = new Backbone.Model([1,2,3,4]);
a.toJSON();//Object {0: 1, 1: 2, 2: 3, 3: 4}
a.attributes;//Object {0: 1, 1: 2, 2: 3, 3: 4} 

無理やり連想配列に変換された・・・

Modelの中にArrayをそのまま保存することはできないみたい。
ArrayとModelは相性悪いです。

Collectionの中身はModelのArrayでModelをセットすると、addとかremoveを発火してくれる。
ただこの中身はModel型しかいれることができない。

Numberとか文字列もいれたいので、Collectionのような挙動をするArrayを書いてみた。
CollectionのようにArrayのひと通りの動作毎にBackbone.Eventでイベントを発火する。

これをつかうとこんな感じの動きになる。

var a = new Backbone.Array([1,2,3,4]);
a.toJSON();//[1, 2, 3, 4]

a.on("change",function(e){console(e)},this);//listenToなど好きなbind関数でも可

a.push(5);//addEventとchangeが発火
a.pop(5);//removeとchangeが発火

ソースはこちら。

Backbone.Modelも格納できるのでCollectionのかわりもできる。

需要あるかわからないけど。

CollectionにModel以外もいれることができてもいいと思うのだけどなぁ・・・

pullRequestおくってみようかな。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?