Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the Ember global 'App' variable in an Ember CLI application?

I am creating an Ember application using the Ember CLI. I have a view which invokes a component that I created. I am trying to access the global App variable to create my component and insert it into my layout.

The error: Uncaught ReferenceError: App is not defined

How do I fix this?

app.js

import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';

Ember.MODEL_FACTORY_INJECTIONS = true;

var App = Ember.Application.extend({
  modulePrefix: 'client-web', // TODO: loaded via config
  Resolver: Resolver
});

loadInitializers(App, 'client-web');

export default App;

item-table.js (This is a view)

import Ember from 'ember';

export default Ember.View.extend({
    templateName: 'item-table',

    didInsertElement: function() {
        // All my other code here

        App.FreestyleChartComponent.create().appendTo($('#wp-chart td')); // This throws an error.
    }
});

app/components/freestyle-chart.js

import Ember from 'ember';

export default Ember.Component.extend({
    templateName: 'components/freestyle-chart',

    didInsertElement: function() {
        console.log('Inserted the component.');
    }
});
like image 520
JackH Avatar asked Sep 17 '14 00:09

JackH


2 Answers

I can think of two ways. The first is to put the App in the global scope manually.

var App = window.App = Ember.Application.extend();

The second is to import the App into your view:

import App from './path/to/app/file';

The latter is only possible if Ember CLI supports circular references. The official ES6 spec supports them but many transpilers don't (mine doesn't).

However, I don't think this is your root concern. For the most part, you shouldn't be accessing global variables in Ember CLI. Instead of placing the FreestyleChartComponent in the App namespace, why not just put it in a module and import it like any other module? Global variables are unavoidable (I experienced that today), but you should try to minimize them.

like image 150
GJK Avatar answered Sep 22 '22 16:09

GJK


I do agree that you should not be accessing your app via the global namespace, however ember-cli actually does actually make you app a global with the name of your app being the name of the variable.

If you open /app/index.html in your ember-cli project you should see a script tag towards the bottom that looks like...

<script>
  window.YourAppName = require('your-app-name/app')['default'].create(YourAppNameENV.APP);
</script>

in the above example YourAppName would be your app available as a global

like image 28
tikotzky Avatar answered Sep 22 '22 16:09

tikotzky