I’m looking back at the Backbone todo list and have a question about the collection.
Here is the code:
window.TodoList = Bacbone.Collection.extend({
model: Todo,
localStorage: new Store("todos"),
done: function() {
return this.filter(function(todo){return todo.get("done")})
},
remaining: function() {
return this.without.apply(this, this.done());
}
})
I understand everything that is going on here, except for the ‘remaining’ function.
The return statement: return this.without.apply(this, this.done()); is using a proxy to an underscore method – _.without
According to Underscore docs, here is what that is for:
without_.without(array, [*values]) Returns a copy of the array with
all instances of the values removed. === is used for the equality
test._.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
So, I get that it is saying to return everything in the collection without a ‘done’ attribute with the value of ‘true’.
What I don’t understand is the ‘apply’ function that is being chained to it. That doesn’t appear in the Backbone docs or the Underscore docs. At least not anywhere I can find it.
Can anyone explain in detail what is going on with those elements in the Return statement?
thisis referring to the collection.applyis a method of javascript functions that allows you to set context of a method and send an array of values to the caller.applyexpects context as the first parameter then anarrayor array-like (such asarguments) which will be passed in as parameters the function.You can do the same thing with
.callexcept the 2nd+ params are comma separated.applyandcallare native to javascript.So…
return this.without.apply(this, this.done());the method
this.done()returns an array, but uses the context of the collection and passes in a series of values to be ignored via thewithoutmethod. Which in turn returns all todos that aren’t done within the collection.Example: