カテゴリー別アーカイブ: その他

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/

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) { 

}});