LoginSignup
2
2

More than 5 years have passed since last update.

Collectionのreduce関数

Posted at

Backbone.jsのcollectionのreduce関数ついて
ちょっとハマったのでメモします。

例えば、以下のようなModelとCollectionがあるとします

demo.js
var Time = Backbone.Model.extend({
    defaults:function(){
        id:"",
        hour:0
    }
});

var TimeList = function(){
    model:Time
});

var Times = new TimeList;

で、あるTimesの中のhourの値の合計を出したい場合、
reduce関数を使うのですが、リファレンスをみてもなかなか
ちゃんと書いていなかった。

http://blog.livedoor.jp/aki_mana/archives/6393344.html
こちらのブログで書いてあったのでちょっとだけ調べてみた

syntaxとしてはこんな感じ

syntax1
var result = Collection.reduce(iterator, [ctx]);

iterator
評価する関数を指定

[ctx]
iteratorで使用するコンテキストを表す。省略可。

 
上記のiteratorに渡す関数

syntax2
var iterator = function( prev, model, idx, models ){}

prev
関数の評価後の値が入ります。初期値は[ctx]で指定された値が入る。
前述の[ctx]の指定しない場合は配列の1番目が渡される。

model
Collectionに入っている値(一要素)が入る。

idx
インデックスです。配列の要素分(処理された回数分)カウントされる。

models
処理するModelの配列、つまりCollectionそのものが入ってる。


以上の引数があり、冒頭の処理を行う場合、以下のようになりました。

reduce.js
var sum = function(prev, model){ return prev + model.get('hours'); };
var total = Times.reduce(sum, 0);
2
2
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
2
2