Jerald
Jerald

Reputation: 4048

How to include javascript files using 'import name from "module-name"' syntax in Ember.js?

I see that Ember.js includes files using 'import name from "module-name"' syntax. For example, in app.js:

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

I want to include my JS files using this method. But I don't know how to do that. Where should I put my JS files? Or should I do something else?

Here is an example. My component:

//file app/components/small-logo.js
import Ember from 'ember';

import Logo from 'library/logo';

export default Ember.Component.extend({
    mouseEnter: function() {
        var logo = new Logo();
        logo.changeColor();
    }
});

Logo - is a big class, that has many functions. On mouseEnter event I want change the logo's color. Also, I want to start animation when this component shows, but I don't know how to execute a function at this time, it will be another one question.

Here is my component's template:

//file app/templates/components/small-logo.hbs
{{#link-to 'index'}}
    <img alt="Logo" src="img/pixel.gif" class="logo">
{{/link-to}}

Here is my js file with class Logo. I don't know how to include it:

//file app/library/logo.js
var Logo = function() {
 ...
}
Logo.prototype.changeColor = function() {
  ...
}

Upvotes: 0

Views: 1146

Answers (1)

Patsy Issa
Patsy Issa

Reputation: 11293

In order to be able to import a function/module you must export it in the file, adding an export default Logo; will make it available for import though.

I also recommend using absolute paths to reference it, in your case applicationName/library/logo.

Another more ember-ish way to do what you are trying to accomplish would be to move the logic into the component.

export default Ember.Component.extend({
    mouseEnter: function() {
        this.changeColor();
    },
    changeColor: function() {
        // your color change logic, you can access the element via this.$()
    }
});

And while we're at it, since you are using the ember-cli you can use ES6 syntax:

const { Component } = Ember;
export default Ember.Component.extend({
  mouseEnter() {
    this.changeColor();
  },
  changeColor() {
    // your color change logic, you can access the element via this.$()
  }
});

Upvotes: 1

Related Questions