0

I'm new to Ember and I'm having an issue with understanding exactly where "reusable" code should go. From what I've found so far, it sounds like this is supposed to be a utility? The only issue I have no idea how to include the class (or any reusable methods) into the controller.

Here's what I'm after

Example class (where would this go?):

'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());
*/
2
  • 1
    why you use es6 class definition, you can use Ember.Object instead, computed properties will be available Commented Mar 24, 2017 at 21:01
  • @Dart For the reason mentioned here: stackoverflow.com/questions/26412628/… it's much easier to debug. Commented Mar 24, 2017 at 22:30

1 Answer 1

2

Create a separate file for your Person class and import it where you need it. Then you can work with your class as you normally would:

// /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');

// ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.