4
4

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.Collectionでデータをフィルタする

Posted at

テキスト入力でデータをフィルターする機能を実装するのに、Backbone.Collection#whereを使って実装してみるメモ。

// ------------ Model/Collection 定義
var Message = Backbone.Model.extend({
  id: 'msg_id',
  // 属性はこんなの
  defaults: {
    sender: 'anonymous',
    text: '',
    createdAt: new Date()
  }
});

var Messages = Backbone.Collection.extend({
    url: '/api/v1/messages',
    model: Message,
    // 大文字小文字無視してデータを検索する
    whereSender: function(name) {
      var senders = _.uniq(this.pluck('sender')),
          exp = new RegExp($.trim(name), 'i'),
          fName = _.find(senders, function(n) { return n.match(exp); });
      return this.where({sender: fName});
    }
  });

// -------------- 使う方
// データのfetchとかしておく
var messages = new Messages();
messages.fetch();

[ snip ]
// clickやらkey event等が発生したら、フィルター用のテキスト入力を取得
var inputSender = $(':text').val();
// フィルターしたデータを再度Backbone.Collectionにする.
filterdMessages = new Message(messages.whereSender(inputSender));
[ snip ]
4
4
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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?