Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js Utility Class

I am new to Ember.js and Javascript in general. I am using ember-cli to create an app that could use a DateUtil class to perform some date manipulation. I noticed that ember-cli has a utilities generator to produce the following boilerplate code in app/utils/date-util.js:

export default function dateUtil() {};

I am wondering how to write a utility so that I can use it across my application. Specifically, as an example, in a controller:

export default Ember.ObjectController.extend({
  startDate: dateUtil.thisMonday()
});

where thisMonday() would return the date of this Monday using moment.js like:

moment({hour:0}).day(1);

There would be many others similar to thisMonday() as part of dateUtil.

like image 455
Anthony Avatar asked Jul 30 '14 22:07

Anthony


2 Answers

You simply need to import the ES6 module that exports your utility function, in each of the controllers that want to use it, like so:

import dateUtil from 'app/utils/date-util';

export default Ember.ObjectController.extend({
  startDate: dateUtil().thisMonday()
});

Note that the path is not necessarily app/utils/... though, you must replace app with the name of the app that you used when initially generating the app. You can verify what this is by looking in app/app.js, and looking for the value of modulePrefix within Ember.Application.extend().

like image 170
bguiz Avatar answered Nov 15 '22 22:11

bguiz


Just import your class using the ES6 module syntax.

import dateUtil from 'app/utils/date-util.js';

References:

  • ES6 modules
  • ember-cli guide on modules
like image 3
bojangle Avatar answered Nov 15 '22 21:11

bojangle