2013-03-06 55 views
1

我很难理解剩余函数如何在下面的代码中工作。backbone js Todo应用程序_underscore.js _.outout

(注释源:http://documentcloud.github.com/backbone/docs/todos.html

我的申请的理解是第一个参数是自变量的上下文和其余是一个数组来作为参数传递到正被应用的功能。

var TodoList = Backbone.Collection.extend({ 
     model: Todo, 
     localStorage: new Backbone.LocalStorage("todos-backbone"), 
     done: function() 
     { 
     return this.filter(function(todo) { return todo.get('done'); }); 
     }, 
     remaining: function() 
     { 
     return this.without.apply(this, this.done()); 
     }, 
}); 

因此:

this.without.apply(此,this.done()); - >翻译成:

without(array of arguments as parameters to without function); 

没有会将第一个参数是一个数组,2,...,N,你想从数组中删除参数。

我不理解这个函数是如何做有用的。我缺少的解释会有所帮助。

回答

0

this.without.apply(this,this.done()); - >翻译为:without(array);

不是。你知道的下划线函数可以作为第一个参数的数组作为方法骨干集合(如下划线链接包装)。让我们假设this.done()计算结果为[x, y, z],那么apply调用转换为

this.without(x, y, z); 

当然,一个更高性能的方法是做到这

return this.filter(function(todo) { return ! todo.get('done'); }); 
//          ^
+0

但如果this.done()返回一个数组,我仍然不理解它如何过滤ou t没有完成的项目。我理解你的这个.filter的例子,但是有一段我必须失踪。 你是说this.without.apply是一个下划线方法,它应用如下所示:this.without(current_collection,array_of_elements_that_are_done?) – 2013-03-06 13:57:47

+0

'apply'不是下划线方法,而是函数对象的本地方法 - 请参阅文档我已经链接上面。 – Bergi 2013-03-06 14:05:50

+0

我理解的方式如下所示:第一个参数是this的上下文,第二个参数是包含函数对象的1 ... n个参数的数组。返回this.without.apply(this,this.done())似乎没有意义,因为this.done()返回已完成的对象数组。我不明白它是如何过滤掉没有完成的项目的 – 2013-03-06 17:56:25

0

骨干:将在每个下划线方法作为代理收藏#模型

_.each(methods, function(method) { 
    Collection.prototype[method] = function() { 
     //convert arguments to array. Such as: args = [1, 2, 3] 
     var args = slice.call(arguments); 
     //add this.models at the begining of array. Such as: [['string'], 1, 2] 
     args.unshift(this.models); 
     //_[without].apply(_, [['string'], 1, 2]) 
     //_.without(['string'], 1, 2); 
     return _[method].apply(_, args); 
    }; 
    });