Accessing an Ember.Mixin within a custom handlebars helper

不打扰是莪最后的温柔 提交于 2019-12-23 06:05:05

问题


Is there an elegant way of using methods defined in an Ember.Mixin object within a custom handlebars helper?

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 (e.g. {{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.

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:

http://emberjs.jsbin.com/wunug/1/edit?html,js,output (look at lines 33-37)


回答1:


The method Mixin.apply makes the job.

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



回答2:


I am using Ember 2.12 and this is what I worked for me. Hopefully this helps somebody.

Create a new mixin named formatter:

../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.

../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:

    {{short-date today}}           


来源:https://stackoverflow.com/questions/23250225/accessing-an-ember-mixin-within-a-custom-handlebars-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!