Question

Previously when I developed ember application I used App as my global object and every class was stored in this big object.

Like this

window.App.MyModel = Em.Object.extend({});

And in the browser console, I was able to do

App.MyModel.create();

So it was really easy for me to access MyModel class.

Now I started experiments with Ember-CLI, I don't have much experience with this kind of tools. I followed the documentations and I created my model Service like this.

var Service = Ember.Object.extend({});
export default Service

But now, how to access Service class from browser console? Only way I found was:

App.__container__.resolve('model:service')

But I don't like it much. Is there better way? Btw, can you please explain how export works? Or is there some source (documentation, article) where I can study it?

Thanks a lot for response.

Was it helpful?

Solution

If you're aiming to have something available in most places throughout your application you'll typically want to register it on the container.

There are multiple ways to access the container, and you're correct in that the one you found was less than ideal. The running joke is "any time you directly access __container__ we need to add more underscores."

To directly control how things are registered on the container and injected into the container you typically want to use an initializer. Using initializers in ember-cli is super-easy, they're executed for you automatically.

Checking out the documentation you can see that you get access to the application's container as an argument which allows you to manipulate it in a safe manner.

Once you have access to the container you can use register and inject to make content easily available in particular locations. This was introduced here. One note, accessing things inside of the container from outside the context of your app (browser console) will require the usage of App.__container__ and that is the expected use pattern.

And the export you're running into is an ES6 module system construct, it's not Ember-specific. Playing with the ES6 module transpiler can give you a good sense of what goes in and what comes out in "we can do this today" type of JavaScript.

OTHER TIPS

For ember 3.22, application classes can be accessed like so:

Ember.Namespace.NAMESPACES[1]._applicationInstances.values().next().value.lookup('service:state-events')

Note, you may need to modify the index in NAMESPACES[1] to be something other than 1. You can determine which namespace is your application when this returns true:

Ember.Namespace.NAMESPACES[1] instanceof Application

This approach is how ember-inspector accesses ember applications: https://github.com/emberjs/ember-inspector/blob/50db91b7bd26b12098cae774a307208fe0a47d75/ember_debug/main.js#L163-L168

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top