在Backbone中如何根据过滤器/查询从集合中删除模型?

时间:2013-10-21 11:38:38

标签: backbone.js jasmine titanium-alloy

我正在使用Backbonejs 0.9.2和Titanium Alloy,我需要从Collection中删除所有已完成的任务。 Backbone.sync配置为使用SQLite本地数据库。

extendCollection: function(Collection) {

    exts = {
      self: this
      , fetchComplete: function() {
        var table = definition.config.adapter.collection_name

        this.fetch({query:'SELECT * from ' + table + ' where complete=1'})
      }
      , removeComplete: function () {
        this.remove(this.fetchComplete())
      }
    }

    _.extend(Collection.prototype, exts);

    return Collection
}

我的Jasmine测试看起来像这样

describe("task model", function () {
    var Alloy = require("alloy"),
        data = {
           taskId: 77
        },
        collection,
        item;

    beforeEach(function(){
        collection = Alloy.createCollection('task');
        item = Alloy.createModel('task');
    });

    // PASSES
    it('can fetch complete tasks', function(){
        item.set(data);
        item.save();

        collection.fetchComplete();
        expect(0).toEqual(collection.length);

        item.markAsComplete();
        item.save();

        collection.fetchComplete();
         expect(1).toEqual(collection.length);
      });

      // FAILS
      it('can remove completed tasks', function(){               
        // we have 6 items
        collection.fetch()
        expect(6).toEqual(collection.length);

        // there are no completed items
        collection.fetchComplete();
        expect(0).toEqual(collection.length);

        item.set(data);
        item.save();
        item.markAsComplete();
        item.save();

         // we have 7 items 1 of which is complete
         collection.fetch()
         expect(7).toEqual(collection.length);
         collection.removeComplete()

         // after removing the complete item we should have 6 left
         collection.fetch()
         expect(6).toEqual(collection.length);
      });

      afterEach(function () {
          item.destroy();
      });
 });

2 个答案:

答案 0 :(得分:0)

遍历您的集合或通过下划线使用一些辅助函数,然后调用remove函数并传入模型。请参阅此处的文档:http://backbonejs.org/#Collection-remove

答案 1 :(得分:0)

或者,您可以使用下划线'_.filter方法::

_.filter(tasks, function (task) {
    return task.status == 'ACTIVE'
});

看到这个小提琴:

http://jsfiddle.net/Y3gPJ/