2012-10-20 30 views
0

我正在尝试过滤集合,然后洗牌过滤的值。在过滤的骨干网集合上调用shuffle

我正在考虑使用Backbone提供的where方法。类似:

myRandomModel = @.where({ someAttribute: true }).shuffle()[0] 

然而,where返回匹配的属性,其中所有型号的阵列;显然shuffle需要列表一起工作:

shuffle_ .shuffle(名单)
返回列表

http://documentcloud.github.com/underscore/#shuffle

的改组副本是否有办法把我的模型阵列变成一个'列表'?或者我应该自己写一些逻辑来完成这件事?

回答

2

shuffle()where()方法只是在骨干藏品下划线方法的代理。下划线方法仍然可以自行工作,并以数组为参数。这里是我会做什么:

myRandomModel = _.shuffle(@.where({ someAttribute: true }))[0] 

参考:http://documentcloud.github.com/underscore/#shuffle

PS:@“万亩太短”是正确的但是,要获得一个单一的模式,我会去的Math.random()方式自己。

0

我把(用Rails 3)在我的application.js文件中的以下内容:

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

当下划线文档说列表,它们的意思是数组。所以,你可以使用_.shuffle这样的:

shuffled = _([1, 2, 3, 4]).shuffle() 

或者你的情况:

_(@where(someAttribute: true)).shuffle() 

然而,由于我们就可以抓取一个单一的模式,你可以简单地生成一个随机指数,而不是洗牌:

matches = @where(someAttribute: true) 
a_model = matches[Math.floor(Math.random() * matches.length)] 
0

首先您的收藏中,你应该有一个过滤功能 像

var MyCollection = Backbone.Collection.extend ({ 
    filtered : function () { 

通常你会用_.filter只得到你想要的车型,但你也可以使用suffle作为替代品使用。模型获取集合模型 这里洗牌将混合

var results = _ .shuffle(this.models) ; 

然后用下划线映射您的结果,并把它转换为JSON 像这样

results = _.map(results, function(model) { return model.toJSON() }); 

最后返回一个新的骨干集,只有结果的模型你可能只返回JSON,如果这是你正在寻找的

return new Backbone.Collection(results) ; 

注意,如果你不想保留集合中的所有数据供以后使用,您可以使用以下内容并忽略下面的视图;

this.reset(results) ;   
    } 
});