Justin
Justin

Reputation: 45340

Ember.js how to concat two objects

I have an object in Ember (let's call it existing):

 var existing = {
     items: [
        ...
     ],
     ...
 }

On the callback of hitting a server side request, there is a new response called result which looks the same as existing. I need to take the items in existing, and prepend them to the new result. So I have the following:

  var result = { ... };
  var existing = this.get('content');
  result.items = result.items.concat(existing.items);
  this.set('content', result);

The problem is, when rendered in the template, it is just displaying the new items from result, the old items from existing are not being displayed even though are in items. Any ideas why?

Thanks.

Upvotes: 2

Views: 6636

Answers (3)

gcoladarci
gcoladarci

Reputation: 1119

I see this is an old post, but since there isn't an accepted answer, I thought I'd throw in what I feel is the best option. I recently found myself needing to concat a bunch of DS.ManyArray together and this was the solution I came up w/:

var myArrayOfHasManyArrays = ...;
var concatenated = [].concat.apply([], myArrayOfHasManyArrays.invoke('toArray'));

Hope this helps!

Upvotes: 0

topherd
topherd

Reputation: 96

If result.items is an array and you want to use the javascript concat method you can call toArray on the existing.items enumerable.

var result = { ... };
var existing = this.get('content');
result.items = result.items.concat(existing.get('items').toArray());
this.set('content', result);

If result.items is already an Ember.Enumerable I would use pushObjects or addObjects. http://emberjs.com/api/classes/Ember.MutableArray.html#method_addObjects

var result = { ... };
var existing = this.get('content.items');
result.items = result.get('items').addObjects(existing);
this.set('content', result);

Upvotes: 0

intuitivepixel
intuitivepixel

Reputation: 23322

I guess the problem is that using concat which is not supported in Ember.Array (http://emberjs.com/api/classes/Ember.Array.html) does not trigger bindings and therefore your view is not updated. To get the items arrays merged you could do something like:

var result = { ... };
var existing = this.get('content');
result.items.forEach(item) {
  existing.items.pushObject(item);
}
this.set('content', existing);

Hope it helps

Upvotes: 2

Related Questions