为什么在此主干 todo-mvc 示例应用程序中需要“应用”

Why is 'apply' necessary in this backbone todo-mvc sample application?

本文关键字:应用 应用程序 todo-mvc 为什么      更新时间:2023-09-26

在 Backbone Todo MVC 源代码中,该函数的本机应用方法用于调用下划线方法,我不明白为什么有必要。

// Filter down the list of all todo items that are finished.
completed: function() {
  return this.filter(function( todo ) {
    return todo.get('completed');
  });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
  return this.without.apply( this, this.completed() );
},

与其他下划线方法(如 filter)相比,对 without 的调用看起来不合适。我仔细检查了 Backbone 源,以确保 without 没有以不同的方式混合到集合对象中。果然不是。

以下是下划线方法附加到集合的方式:

_.each(methods, function(method) {
  Collection.prototype[method] = function() {
    var args = slice.call(arguments);
    args.unshift(this.models);
    return _[method].apply(_, args);
  };
});

正如预期的那样 - 集合的模型已作为第一个参数传递。此外,由于这些方法是在 Collection 对象上调用的,因此这将正确绑定。

我通过将方法更改为以下内容来验证这一点

this.without(this.completed());

这很好用。

我在这里忽略了什么?

我不认为你忽略了任何东西。这只是对apply不必要的调用。可能作者最初写了以下内容(也许是为了早期版本的 Backbone)。

// Filter down the list to only todo items that are still not finished.
remaining: function() {
  return _.without.apply( this, this.completed() );
},

Underscore 的without将数组作为其第一个参数,并为以下参数从数组中排除值列表。在 Backbone 的情况下,底层方法正在处理的数组是集合 (collection.models) 内的模型数组,要排除的值列表是已完成的待办事项。所以它本质上是

_.without.apply(collection.models, this.completed())

如果没有apply则数组作为第二个参数传递给_.without,这将尝试从数组中排除数组

_.without(collection.models, [completedTodo1, completedTodo2 /* , etc */]);

但是在apply,完成的待办事项作为单独的参数传递,即:

_.without(collection.models, completedTodo1, completedTodo2 /* , etc. */) 

这是您想要的,以便它将排除每个已完成的待办事项。