Question

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)

Was it helpful?

Solution

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);
});

OTHER TIPS

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}}           
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top