2
votes

I am trying to grasp the underlying system of Ember.JS. Whereto are those Ember-Objects exported and how are they used?

components:

export default Ember.Component.extend({ ... });

controllers:

export default Ember.Controller.extend({ ... });

models:

export default DS.Model.extend({ ... });

routes:

export default Ember.Route.extend({ ... });

... they all follow the same structure: they extend some object and export something.

Somebody knows more? Thanks!

1

1 Answers

4
votes

I think you are interpreting the export keyword wrong here.

It doesn't mean files are written somewhere else in a different format, but:

if a module (= file) is imported, then things in that file that are exported are available to the importer.

Think of it as making some parts available to other modules, a public API in shorter terms.

Ember files usually only export one thing as there is a strong naming convention making the Ember engine work that way.
This is why if you declare a /user route, it will try to use your routes/user.js, controllers/user.js, and templates/user.hbs files if they exist, without you having to specify anything. In a similar way, this is what makes a component usable inside a template.

Hence the one-liner export default Ember.Something.extend({ ... }); you find in these files.

However, you can have modules (= files) with multiple export statements in a single file, this is perfectly valid.

// Example from babel website

// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
    return Math.exp(x);
}
// app.js
import exp, {pi, e} from "lib/mathplusplus";
console.log("e^π = " + exp(pi));

The Learn ES2015 from Babel website has a few examples, and you can read more about the export statement on MDN.

In Ember applications, you will - from my experience - find files with multiple exports mostly in some directories meant to be used by more than one module in the application, or not bound to the Ember engine auto-import, like some utils.

The following example shows an Ember.Controller importing a variable exported from another module:

// utils/messages.js
export var hello = 'Hello!';
export var bye = 'Good Bye!'

// controllers/hello.js
import { hello } from "utils/messages";

export default Ember.Controller.extend({
  firstName: 'David',

  helloString: Ember.computed('firstName', function(){
    return `${hello} ${this.get('firstName')}`;
  })
});