2014-12-04 46 views
1

我有一個按鈕,點擊後在我的Ember站點中加載一條新路線並返回一個對象數組。我想要做的就是設置它,以便單擊此按鈕會導致該數組中的隨機對象在模板中呈現。這樣用戶每次點擊都可以得到不同的結果。我不知道如何告訴它選擇一個隨機索引並將其呈現在我的句柄模板中。任何幫助,將不勝感激。我對Ember很新。EmberJS - 在對象數組中生成隨機對象

這是我的路線正在被加載(但不顯示內容):

App.GenerateRoute = Ember.Route.extend({ 
    model: function(){ 
     return App.GENERATE; 
    } 
}); 


App.GENERATE = [ 
    { 
    id: 1, 
    word: //word here, 
    language: //language here', 
    trans: //translation here' 
    }, 
    { 
    id: 2, 
    word: //word here, 
    language: //language here', 
    trans: //translation here' 
    }, 
    { 
    id: 3, 
    word: //word here, 
    language: //language here', 
    trans: //translation here' 
    } 
]; 
+0

要選擇一個數組中的隨機對象並呈現爲把手?或隨機隨機混合並顯示整個數組? – Ajey 2014-12-04 07:03:08

回答

2

你可以使用車把實現這一目標。 將模型傳遞給把手功能,然後用一點JavaScript魔術,從數組中選擇一個隨機對象,然後渲染。

Ember.Handlebars.helper('randomize', function(myArray, options) { 

    return myArray[Math.floor(Math.random() * myArray.length)].id; 
}); 

你調用這個方法輔助方法 -

{{ randomize model}} 

Demo

隨機對象返回每次刷新時間或打route

+0

真棒!謝謝!歡迎您來到 – purcelllj 2014-12-04 08:38:44

+0

.. – Ajey 2014-12-04 09:12:30