将每个Underscore方法混合为Collection#models的代理

Mar*_*ria 5 javascript backbone.js underscore.js

我正在使用骨干库来执行以下操作:

var Persons = Backbone.Collection.extend({
    defaults: {
        name: 'unknown',
        age: 18
    },

    over_18: function () {
        return this.filter(function (model) {
            return model.get('age') > 18
        });
    },

    under_18: function () {

        var persons_over_18 = this.over_18;

        return this.without(this, persons_over_18); // it does not work!! why?
    }
});

persons = new Persons([{age: 17}, {age: 27}, {age:31} ]);

persons.under_18().length; // 3 instead of 1
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该方法under_18无法正常工作,因为它返回所有模型,而不是只给出年龄属性小于18的模型.

所以为了调试我的代码,我决定看看Backbone.js Annotated Source,特别是下面的代码:

var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', ... ]; // and more

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

但上面的代码对我来说并不清楚,我仍然不能按照自己的意愿使第一个代码工作.

所以我的问题是如何修复与第二个相关的第一个代码?

这是我的代码到jsfiddle.net http://jsfiddle.net/tVmTM/176/

Mat*_*ain 0

1) methods数组中的每个字符串对应一个下划线方法,如_.forEach_.map等。函数_.reduce中的每个字符串methods都被添加到Collection调用该下划线方法的原型中,但将集合中的模型作为第一个参数传递,后跟任何你传入的选项。

例如,假设您有一个名为 的集合Dogs,其中包含一堆Dog模型。调用Dogs.forEach(options)将调用一个调用 的函数_.forEach(Dogs.models, options)。这是一个方便的事情。

2)在第2行,that当我认为你的意思是时,你使用this.在第 3 行之后,您有一个额外的without