我试图过滤一个Collection,然后对过滤后的值进行随机播放。
我正在考虑使用Backbone提供的where
方法。类似的东西:
myRandomModel = @.where({ someAttribute: true }).shuffle()[0]
但是,where
会返回与属性匹配的所有模型的数组;显然shuffle
需要列表才能使用:
shuffle _ .shuffle(list)
返回列表的混洗副本
http://documentcloud.github.com/underscore/#shuffle
有没有办法将我的模型阵列变成一个列表'?或者我应该自己写一些逻辑来完成这项工作?
答案 0 :(得分:3)
当Underscore文档说 list 时,它们表示 array 。所以你可以像这样使用_.shuffle
:
shuffled = _([1, 2, 3, 4]).shuffle()
或者在你的情况下:
_(@where(someAttribute: true)).shuffle()
然而,由于你只是抓住一个模型,你可以简单地生成随机索引而不是改组:
matches = @where(someAttribute: true)
a_model = matches[Math.floor(Math.random() * matches.length)]
答案 1 :(得分:2)
shuffle()
和where()
方法只是Backbone集合中代表下划线方法的代理。下划线方法仍然可以自己工作,数组作为参数。这就是我要做的事情:
myRandomModel = _.shuffle(@.where({ someAttribute: true }))[0]
参考:http://documentcloud.github.com/underscore/#shuffle
PS:@“mu太短”是对的,为了得到一个模型我会自己走Math.random()
方式。
答案 2 :(得分:0)
我将以下内容放在application.js文件中(使用Rails 3):
Array.prototype.shuffleArray = function() {
var i = this.length, j, tempi, tempj;
if ( i === 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
tempi = this[i];
tempj = this[j];
this[i] = tempj;
this[j] = tempi;
}
return this;
};
现在我可以在一个数组数组上调用shuffleArray()。暂时没有答案,因为我想知道是否有更好的方法来使用Underscore / Backbone。
答案 3 :(得分:0)
首先在你的收藏中你应该有一个过滤功能 像
var MyCollection = Backbone.Collection.extend ({
filtered : function ( ) {
通常你会使用_.filter来获取你想要的模型,但是你也可以使用suffle作为替换使用this.models来获取集合模型 这里shuffle将混合模型
var results = _ .shuffle( this.models ) ;
然后使用下划线映射您的结果并将其转换为JSON 像这样
results = _.map( results, function( model ) { return model.toJSON() } );
最终返回一个新的主干集合,只有结果你可能只返回json,如果你正在寻找
return new Backbone.Collection( results ) ;
请注意,如果您不想将所有数据保留在集合中供以后使用,则可以使用以下内容并忽略下面的视图;
this.reset( results ) ;
}
});