我想使用 _.without
方法过滤 Backbone 集合
。
它以这种调用形式返回正确的结果(仅完成的 Todos):
return this.without.apply(this, this.active());
但不是这个:
return _.without(this.models, this.active());
在后一个语句中,它返回包含集合中的ALL模型的数组。
我不能直接使用 Underscore
方法,而只能通过 Backbone 的 this
上下文吗?
如何使第二条语句起作用?
todos.js
var app = app || {};
var Todos = Backbone.Collection.extend({
model: app.Todo,
active: function() {
return this.filter(function(todo) {
return todo.get('completed') === false;
});
},
completed: function() {
return this.without.apply(this, this.active());
// return _.without(this.models, this.active()); <--- Problem is here
}
});
app.Todos = new Todos();
稍后添加:
由于 _.without
方法不接受数组作为第二个参数 _.difference
更适合我的任务。
return _.difference(this.models, this.active());
最佳答案
问题在于您使用了 Undersore 的 without
方法不当。它期望第二个参数为标量值,而您传递数组
。
实际上你根本不需要_.without
。
不要尝试在 completed
方法中重用您的 active
方法。这是一种不好的做法。 completed
方法必须通过与 active
相同的方法来实现。
所以代码应该如下所示:
var Todos = Backbone.Collection.extend({
model: app.Todo,
active: function() {
return this.filter(function(todo) {
return todo.get('completed') === false;
});
},
completed: function() {
return this.filter(function(todo) {
return todo.get('completed') === true;
});
}
});
更新:
问:那么为什么第一次调用(使用 apply
)有效呢?
答:因为apply
方法将 this.active()
结果(即 array
)转换为值列表,这正是 _.without
方法所期望的。因此,此调用的工作方式与第二个调用不同,第二个调用不等同于第一个调用。
但是,如上所述,强烈不推荐这种类型的代码重用,因为除了双数组处理开销之外,它还模糊了代码逻辑。
关于javascript - 为什么 'without' 方法根据上下文返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26202350/