Backbone.js 在主干网中,如何基于过滤器/查询从集合中删除模型?
我正在使用钛合金Backbonejs 0.9.2,我需要从集合中删除所有已完成的任务。Backbone.sync配置为使用SQLite本地数据库Backbone.js 在主干网中,如何基于过滤器/查询从集合中删除模型?,backbone.js,jasmine,titanium-alloy,Backbone.js,Jasmine,Titanium Alloy,我正在使用钛合金Backbonejs 0.9.2,我需要从集合中删除所有已完成的任务。Backbone.sync配置为使用SQLite本地数据库 extendCollection: function(Collection) { exts = { self: this , fetchComplete: function() { var table = definition.config.adapter.collection_name
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();
});
});
通过下划线遍历集合或使用一些帮助函数,然后调用remove函数并传入模型。请参阅此处的文档:或者,您可以使用下划线的方法: 看这把小提琴:
感谢您的回复-如何引用
removeComplete
中的收藏?对于this.fetchComplete()
我得到了未定义的,我对您的代码进行了分叉,并对where
方法进行了一些更改。它不像我期望的那样工作。你能告诉我我做错了什么吗?我不熟悉Backbone,其中是下划线方法,因此应使用\uu调用它。在\ucode>中,您缺少\ucode>,因为removeComplete
是该集合的一个函数,通过this
可以获得当前主干的参考。收集对象如果我有点胖,很抱歉,但这不是where
收集方法吗。如果this
是当前集合,它还没有使用我的自定义函数扩展过吗,即fetchComplete
是的,您是对的,还有一个主干方法叫做,其中,在这个小提琴中(基于您的代码),我可以访问fetchComplete
方法(如预期的那样):
_.filter(tasks, function (task) {
return task.status == 'ACTIVE'
});