2012-01-30 22 views
35

Puedo incluir una matriz en un objeto Ember y mostrar los contenidos usando manubrios. Sin embargo, solo puedo reemplazar los contenidos de la matriz usando set(). ¿Cómo puedo modificar los contenidos de la matriz usando push/pop/etc. y todavía tienen la actualización de enlaces UI?¿Cómo hacer push/pop arrays en 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}} 

Respuesta

68

Para trabajar con colecciones, Ember.js proporciona una clase contenedora Array, Ember.Array/Ember.MutableArray

Así, en lugar de utilizar un array plano, utilice los siguientes:

// 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

Perfecto. ¡Gracias! –

+7

Referencia útil para pushObject y sus amigos (popObject, removeAt, etc): http://ember-docs.herokuapp.com/symbols/Ember.MutableArray.html –

+1

Aquí también es útil la respuesta por la cual necesita usar esos métodos: http : //stackoverflow.com/questions/14582759/ember-containerview-not-updating-in-response-to-childviews-push – zigomir

0

Utilice una instancia de Ember.ArrayController, simplemente declarando una matriz con [] también creará una matriz de la clase Ember.ArrayController.

Si desea agregar un objeto al final de Ember ArrayController puede usar el método addObject();

por ejemplo.

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

Es mejor evitar el uso de Ember.ArrayController ahora, ya que ha quedado obsoleto. Utilice las clases Ember.Array o Ember.ArrayProxy en su lugar. – SeanK