简体   繁体   English

在自定义车把助手中访问Ember.Mixin

[英]Accessing an Ember.Mixin within a custom handlebars helper

Is there an elegant way of using methods defined in an Ember.Mixin object within a custom handlebars helper? 是否有一种优雅的方式使用自定义车把帮助器中的Ember.Mixin对象中定义的方法?

For example, in my case I have a mixin, App.Format which contains a bunch of different methods for formatting numbers, dates, ect and I would like to make some of these methods accessible directly from templates via custom helpers (eg {{formatNumber 450324}} ). 例如,在我的情况下,我有一个混入App.Format ,其中包含一堆用于格式化数字,日期等的不同方法,我想通过自定义帮助程序直接从模板中访问其中一些方法(例如{{formatNumber 450324}} )。 The reason I don't just put the method implementation directly in the helper instead of the mixin is that I also need these methods to be available in controllers, views, ect. 我之所以将方法实现不直接放在助手中而不是在混合器中,是因为我还需要这些方法在控制器,视图等中可用。 And in the interest of keeping my code DRY, I definitely do not want to have duplicate code in the mixin and the helpers. 为了使我的代码保持干燥,我绝对不希望在mixin和帮助器中有重复的代码。

Is there any canonical, "emberish" way to accomplish this, or am I just thinking about it in the completely wrong way altogether? 是否有任何规范的,“淡淡的”方式来完成此任务,或者我只是完全以完全错误的方式来考虑它?

Edit: Here is a jsbin to better illustrate the problem: 编辑:这是一个jsbin,可以更好地说明问题:

http://emberjs.jsbin.com/wunug/1/edit?html,js,output (look at lines 33-37) http://emberjs.jsbin.com/wunug/1/edit?html,js,输出 (请查看第33-37行)

The method Mixin.apply makes the job. Mixin.apply方法可以完成这项工作。

Ember.Handlebars.helper('formatNumber', function(num, decimals) {
  var format = App.Format.apply({});
  return format.formatNumber(num, decimals || 2);
});

I am using Ember 2.12 and this is what I worked for me. 我正在使用Ember 2.12,这就是我的工作。 Hopefully this helps somebody. 希望这对某人有帮助。

Create a new mixin named formatter: 创建一个名为formatter的新mixin:

../mixins/formatters.js ../mixins/formatters.js

    import Ember from 'ember';

    export default Ember.Mixin.create({
        shortDate: function(date) {
            return `Date should be formatted: ${date}`;
        }
    });

Create a new helper that imports the above mixin and uses it. 创建一个新的助手,该助手将导入上面的mixin并使用它。

../helpers/short-date.js ../helpers/short-date.js

    import Ember from 'ember';
    import FormatDateMixin from '../mixins/formatters';

    export default Ember.Helper.extend(FormatDateMixin,  {
      compute: function(params /*, hash*/) {
        return this.shortDate(params);
      }
    });

In the template *.hbs file, use the helper as below: 在模板* .hbs文件中,使用如下所示的帮助程序:

    {{short-date today}}           

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

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