Ember JS如何实现正常的ES6类

时间:2017-03-24 20:41:50

标签: javascript ember.js

我是Ember的新手,我在确切地了解哪些地方可以重复使用"代码应该去。从我到目前为止发现的情况来看,听起来这应该是一个实用工具?唯一的问题我不知道如何将类(或任何可重用的方法)包含在控制器中。

这是<我在

之后的事情

示例类(这会去哪里?):

'use strict'

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    getPerson(){
        return "My name is " + this.name + " and I'm " + this.age + " years old";
    }
}

/app/routes/index.js:

import Ember from 'ember';
export default Ember.Route.extend({
    beforeModel(){
        this.replaceWith('rentals');
    }
});

/* How would I include the class so I could call the below??
    var person1 = new Person('Bob', '15');
    var person2 = new Person('Kevin', '41');
    console.log(person1.getPerson());
    console.log(person2.getPerson());
*/

1 个答案:

答案 0 :(得分:2)

Person类创建一个单独的文件,并将其导入到您需要的位置。然后你可以像往常一样与你的班级一起工作:

// /app/util/Person.js

export default class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }

    getPerson(){
        return "My name is " + this.name + " and I'm " + this.age + " years old";
    }
}


// /app/routes/index.js

import Ember from 'ember';
import Person from '../util/Person';

// ...

const person1 = new Person('Bob', '15');

// ...