2012-01-30 20 views
35

Posso includere un array in un oggetto Ember e visualizzare il contenuto utilizzando Handlebars. Tuttavia, posso solo sostituire il contenuto dell'array usando set(). Come posso modificare i contenuti dell'array usando push/pop/etc. e hanno ancora l'aggiornamento dei binding UI?Come spingere/schioccare gli array in Ember.js?

// JS 
App.obj = Ember.Object.create({ 
    "things": ["1", "2"], 
}); 
App.obj.set("things", ["1", "2", "3"]); // Works 
App.obj.things.push("3"); // Doesn't Work 

// HTML + Handlebars 
{{#with App.obj}} 
    <ul> 
    {{#each things}} 
     <li>{{this}}</li> 
    {{/each}} 
    </ul> 
{{/with}} 

risposta

68

Per lavorare con le collezioni, Ember.js fornisce una classe wrapper Array, Ember.Array/Ember.MutableArray

Così, invece di utilizzare una matrice piana, utilizzare questi:

// JS 
App.obj = Ember.Object.create({ 
    "things": Ember.A(["1", "2"]) 
}); 
App.obj.things.pushObject("3"); // pushObject notifies observers 

// HTML + Handlebars 
{{#with App.obj}} 
    <ul> 
    {{#each things}} 
     <li>{{this}}</li> 
    {{/each}} 
    </ul> 
{{/with}} 
+0

Perfetto. Grazie! –

+7

di riferimento utili per pushObject ed esso amici (popObject, RemoveAt, ecc): http://ember-docs.herokuapp.com/symbols/Ember.MutableArray.html –

+1

qui è anche risposta utile perché è necessario utilizzare gli stessi metodi: http : //stackoverflow.com/questions/14582759/ember-containerview-not-updating-in-response-to-childviews-push – zigomir

0

Usa un'istanza di Ember.ArrayController, dichiarando semplicemente che un array con [] creerà anche un array di classe Ember.ArrayController.

Se si desidera aggiungere un oggetto alla fine di Ember ArrayController, è possibile utilizzare il metodo addObject();

es.

mutableArray:[], 

setModel:function(){ 

var data1={'id':1,'name':'over'}; 
var data2={'id':3,'name':'out'}; 

this.get('mutableArray').addObject(data1); 
this.get('mutableArray').addObject(data2); 

/* To Add Object to middle of array at given index simply use the native array splice method */ 

var data1={'id':2,'name':'and'} 
this.get('mutableArray').splice(1,0,data1); 

return this.get('mutableArray') 

}.property('mutableArray') 
+3

Meglio evitare di utilizzare Ember.ArrayController ora poiché è stato deprecato. Utilizzare invece le classi Ember.Array o Ember.ArrayProxy. – SeanK