How to use nested objects/properties from external API in Ember?


#1

Hi,

1st - I’m new to ember and I’m trying to understand how everything works yet.

2nd - I’ve searched on stackoverflow and here for a solutiion, but couldn’t find anything, probably because I don’t know exactly what is the term to look for =P

Well, the situation is as follow…

I have an API that I made before start using ember, and now I’m trying to use this API with my ember app, but when I try to use some of the properties from this API, if a internal function changes the property, ember throws an Uncaught Error like this:

Assertion Failed: You must use Ember.set() to access this property (of [object Object])

This only happens when I’m using a nested object, I’ve made this jsbin for better understanding.

http://jsbin.com/qajukepa/1/

Open the browser console panel, and you’ll can see the error when you click on the change button.

When I change the first property (a “direct value” assigned to ember) everything is ok, but the second one throws the error.

Is there any way to avoid this, it’s a known bug or something?

I need to keep the API as is, beacause it’s being used in other projects that doesn’t use ember.

Thanks in advance.


#2

As the error states, you must use Ember.set() to update the property (and to make sure it’s updated in your template).

If you replace your code in API.changeObj2 with Ember.set(API.obj2, 'n', value); the error goes away.

The nice thing about Ember.set() and Ember.get() is that they work with POJOs too. @machty did two great videos on the subject: https://www.youtube.com/watch?v=h4w7ZqCk0zg and https://www.youtube.com/watch?v=BIaQk8D4lV8


#3

The problem is that this API needs to work regardless of Ember, because it is used in enviroments that may or may not use it.

I’ve managed to get it working using a cloned object instead the direct reference.

So I’m doing this in the Controller

@set('ember_property', $.extend({}, API.nested_object))

And my API has a callback implementation that notify changes on the exposed properties that the app may use, so I can bind a function to update the property in ember too…

Like this

self = @
API.on 'someaction', ()->
  self.set('ember_property', $.extend({}, API.nested_object)

I just thought that was some other way of using exposed objects from an external API without having to do this cloning workaround.

Later on I plan to create an Ember compliant version of the API, but for now it’s pratically impossible to refactor 15k lines of code due to project deadline. =P

Thanks.