Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn nested plain js objects into Ember.js objects?

If I have a nested set of plain old javascript objects (for example, having been returned from JSON), how do I them into Ember.js objects (or at least getting the binding functionality working)?

For example, if I have an object like:

var x = {
  bar: {
    baz: "quux"
  }
}

Then I turn that into an Ember object:

var y = Ember.Object.create(x);

Then setting the value of "baz" won't update any views I have, because it is just a normal js object, not an Ember object.

I know I can just recursively go over the object keys, and do Ember.Object.create all the way down, but is there an alternative approach?

like image 325
Roland Avatar asked Jan 12 '12 16:01

Roland


1 Answers

I'm not sure how you're attempting to set the value of baz, after you've created the Ember.Object, but you should make sure you use an observer-aware setter function. For this example, I'd suggest using setPath().

For example:

var x = {
  bar: {
    baz: "quux"
  }
};
var y = Ember.Object.create(x);
y.setPath('bar.baz', 'foo');

jsFiddle example, showing a view update after setting: http://jsfiddle.net/ebryn/kv3cU/

like image 188
ebryn Avatar answered Oct 29 '22 09:10

ebryn