Collection のparse

コレクションのparseは、内部でモデルのparseを呼び出して、最終的なモデルのインスタンスを取得している。

var Customers = Backbone.Collection.extend({
  model : Customer,
  url : "/cakephp_service/customers",
  parse: function(data){
    return data;
  }
});

Collection 操作

メソッド名 呼び出し方 説明
add add(Modelオブジェクト, オプション) CollectionにModelオブジェクトを追加するとaddイベントが発生する。オプションに{silent:true}を渡すことで、addイベントの発生を抑制できる
get get(Model オブジェクトのid) 指定したid を持つModelを探して取得する。Model に変更するとModel のchangeイベントがそのままCollectionのchangeイベントとして発生する
remove remove(Model オブジェクト, オプション) CollectionからModelオブジェクトを削除するとremoveイベントが発生する。オプションに{silent:true}を渡すことで、removeイベントの発生を抑制できる
reset reset(Modelオブジェクトの配列) 指定したModelオブジェクトの配列でコレクションをリセットするとresetイベントが発生する。オプションに{silent:true}を渡すことで、resetイベントの発生を抑制できる

fetchのタイミング

//collection に変化があったら、render呼び出し

<code>this.listenTo(this.collections, 'all', this.render );</code>

//fetchでデータ取得

this.collections.fetch({silent: true});

//renderする

render: function () {
 console.log(this.collections.get('item').length);
}

とした時、fetch() の先で、ajax なりでデータをサーバーから取得するタイミングによって、item自体がなかったりするので、

render: function () {
 if(this.collections.has('item')){ //あるかどうかチェック
  console.log(this.collections.get('item').length);
 }
}

とするか、

this.model.fetch({ 
       success: this.render // $.ajax 'success' callback
});

とするか。後者は、ちょっと意味が違う。

そういうのがもろもろ書かれている。
http://chilipepperdesign.com/2013/01/15/backbone-js-bind-callback-to-successful-model-fetch/

model にクエリ文字を渡したい場合

options の値が内部では jQuery.ajax に渡されるので、/api/blogs/1?foo=bar のようにクエリ文字を渡したい場合は次のように書く。

var Blog = Backbone.Model.extend({
    defaults: {
        "dateTime": new Date().toISOString()
    },
    initialize: function (attrs, options) {
    },
    validate: function (attrs) {
        if (attrs.text.length === 0) {
            return "本文が入力されていません";
        }
    }
});
blog.fetch({data: {foo: "bar"}});

viewのrender

viewは、render();をもっている。
デフォルトではthisを返すだけなので、関数をオーバーライドする。
render() は、thisを返すというのが暗黙のルール。
つまりthis.render()すれば、return viewしなくてもthisを返す。

fetch

collection.fetch([options])

fetch()で引数がない場合。

var c = new Backbone.Collection();
c.localStorage = new Backbone.LocalStorage("items");
c.fetch();
console.log(c.pluck('id'));

通常は、collection.fetch();を実行すると、ajaxが始まり、collection内でurlを指定していないと、エラーが出る。Backbone.LocalStorageは、デフォルトのajax開始の代わりに、locaclStrageを使用するプラグイン。

collection.fetch({
 datatype: jsonp, 
 data: params, 
 success: function (collection, res, options) { 

}});