gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:21:21 25 4
gpt4 key购买 nike

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

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(', ');
}

还有一把 fiddle http://jsfiddle.net/nikoshr/pxpon64q/

关于javascript - 在集合中的 _.map 中使用模型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32904303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com