我想用_.without
方法過濾Backbone collection
。爲什麼'不'方法根據上下文返回不同的結果?
它返回正確的結果(僅完成託多斯)以這種形式調用:
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());
但是如果_a沒有在第一種形式的調用中工作,如果它期望一個標量值? this.without。apply(this,this.active()) – yaru 2014-10-05 13:17:58
>這是一個不好的習慣爲什麼這樣?這是一個代碼重用。 DRY原則。 – yaru 2014-10-05 13:19:03
_爲什麼這樣?這是一個代碼重用_不適合你的情況 – hindmost 2014-10-05 13:19:50