情景:
如果不是冗长的话,我找不到怎么做:
_.filter(... function (id) { return id==1 || id==3 })
问题:在underscore.js中是否存在此类someMethod1
?
var frdsArr =
[
{id: 1, name: 'moe', age: 40},
{id: 2, name: 'larry', age: 50},
{id: 3, name: 'curly', age: 60}
];
var goodFrdsArr = _.someMethod1( frdsArr, 'id', [1, 3] );
/*
goodFrdsArr is [
{id: 1, name: 'moe', age: 40},
{id: 3, name: 'curly', age: 60}
];
*/
与backbone.js相同的问题:someMethod2
怎么办?
var Friend = Backbone.Model.extend({});
var FriendsCollection = Backbone.Collection.extend({
model: Friend
});
var friendsCollection = new FriendsCollection( frdsArr );
var goodFriendsCollection = friendsCollection.someMethod2( 'id', [1,3] );
/*
goodFriendsCollection contains 2 instances of Friend Models
*/
答案 0 :(得分:1)
找到合适的功能后,您可以使用_.mixin
扩展Underscore,以简化以后的通话。例如,您可以创建_.restrict
以匹配您的_.someMethod1
签名:
_.mixin({
// filter a list on an attribute having to match a list of values
// _.indexOf accepts an optional isSorted argument so let's pass it
restrict: function(list, attr, values, isSorted) {
return _.filter(list, function(obj) {
return _.indexOf(values, obj[attr], isSorted) !== -1;
});
}
});
var goodFrdsArr = _.restrict(frdsArr, 'id', [1, 3]);
请参阅http://jsfiddle.net/nikoshr/cf0qs5gh/了解演示
通过此设置,您可以修改Backbone.Collection
的原型,为您的所有馆藏提供这种新容量(或多或少取自Backbone源代码):
Backbone.Collection.prototype.restrict = function() {
var args = [].slice.call(arguments);
args.unshift(this.models);
return _.restrict.apply(_, args);
};
var friendsCollection = new Backbone.Collection(frdsArr);
var goodfriends = c.restrict('id', [1, 3]); //an array with 2 models
答案 1 :(得分:0)
var frdsArr =
[
{id: 1, name: 'moe', age: 40},
{id: 2, name: 'larry', age: 50},
{id: 3, name: 'curly', age: 60}
];
var filteredIDs = [1,3];
var filteredFrnds = _.filter(frdsArr, function(frnd){
return _.contains(filteredIDs, frnd.id);
})
console.log(filteredFrnds);
<强> FIDDLE 强>