2012-10-20 29 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) ;   
    } 
});