0

我正在使用带有钛合金的 Backbonejs 0.9.2,我需要从集合中删除所有已完成的任务。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
}

我的茉莉花测试看起来像这样

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();
      });
 });
4

2 回答 2

0

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

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

看到这个小提琴:

http://jsfiddle.net/Y3gPJ/

于 2013-10-21T12:01:54.890 回答
0

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

于 2013-10-21T11:49:54.257 回答