LoginSignup
38
41

More than 5 years have passed since last update.

TwitterやQiitaのような自動更新タイムラインをBackbone.jsで作成

Last updated at Posted at 2012-03-16

Qiitaでは新しい投稿がある場合にその件数を表示し,クリックするとタイムラインに追加するということをやっています.TwitterやFacebookと同じ仕組みですね.
これはBackbone.jsのBackbone.Collection#fetchを使うと簡単に実装できます.

コード

// アイテムのコレクションを実装
var TimelineItems = Backbone.Collection.extend({
        model: Item // 投稿のモデル
 });
// 新規投稿のみを取得する
// "/items?after=123"でid:123以降のアイテム情報がJSONで返ってくる想定
TimelineItems.fetch({ url: '/items?after=' + TimelineItems.models[0].id, add: true });

add: trueをfetchの引数に渡すことで,fetchしたときに返ってきたデータをcollectionに追加することができます.あとはViewに適切にイベントを設定しておけば,fetchによってビューの見た目が更新されます.
イベントまわりの話はBackbone.js入門 「View と Model と Collection の連携」でわかりやすく説明されています.
このfetchを定期的に呼んでやることで自動更新タイムラインを作ることができます.

setInterval(function() {
    TimelineItems.fetch({ url: '/items?after=' + TimelineItems.models[0].id, add: true });
}, 1000 * 180);

ざっくりとした説明でしたが,fetchをうまく使うことで取得した投稿の管理やビューの更新を簡単に行うことができます:)

38
41
1

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
38
41