在集合中使用 _.map 中的模型函数

using a model's function in _.map from within a collection

我使用 backbonejs 和 underscorejs。我有一个带有 getFullName() 函数的 Person 模型和一个带有 getSummary()Persons 集合,其中应该 return 包含人员的所有全名。我当前的实现是:

var Person = Backbone.Model.extend({
    defaults: {
        name: '',
        surname: ''
    },
    getFullName: function() {
        return this.get('name') + ' ' + this.get('surname');
    }
});

var Persons = Backbone.Collection.extend({
    model: Person,
    getSummary: function() {
        return _.map(this.models, function(person) {
            return person.getFullName();
        }).join(', ');
    }
});

console.log(
    new Persons([
        {name: 'john', surname: 'smith'},
        {name: 'mary', surname: 'poppins'}
    ]).getSummary()
);

这很好用,我在控制台中显示了以下内容:

john smith, mary poppins

我的问题是我不想在 getSummary() 函数中如此冗长。我希望能够简单地传递模型的函数,而不必创建一个函数来调用它。也许是这样的:

getSummary: function() {
    return _.map(this.models, 'model.getFullName').join(', ');
}

这有可能吗?

Backbone 在集合和模型上代理了很多 Underscore 函数,最值得注意的是非常好的 _.invoke :

invoke _.invoke(list, methodName, *arguments)
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

你可以这样简化你的方法:

getSummary: function() {
    return this.invoke('getFullName').join(', ');
}

还有一个Fiddlehttp://jsfiddle.net/nikoshr/pxpon64q/