简体   繁体   English

Ember.js实用工具类

[英]Ember.js Utility Class

I am new to Ember.js and Javascript in general. 我是Ember.js和Javascript的新手。 I am using ember-cli to create an app that could use a DateUtil class to perform some date manipulation. 我正在使用ember-cli创建一个可以使用DateUtil类来执行某些日期操作的应用程序。 I noticed that ember-cli has a utilities generator to produce the following boilerplate code in app/utils/date-util.js: 我注意到ember-cli有一个实用程序生成器,可以在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: thisMonday()将使用moment.js返回本周一的日期:

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

There would be many others similar to thisMonday() as part of dateUtil. 作为dateUtil的一部分,还有许多其他类似于thisMonday()的东西。

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: 您只需要在每个想要使用它的控制器中导入导出实用程序功能的ES6模块,如下所示:

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. 请注意,路径不一定是app/utils/...但是,您必须将app替换为最初生成应用时使用的应用程序的名称。 You can verify what this is by looking in app/app.js , and looking for the value of modulePrefix within Ember.Application.extend() . 您可以通过查看app/app.js并在Ember.Application.extend()modulePrefix Ember.Application.extend()的值来验证这是什么。

Just import your class using the ES6 module syntax. 只需使用ES6模块语法导入您的类。

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

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM