Search code examples
javascriptember.jshandlebars.js

Ember js use handlebars helper inside a controller?


I have a helper method that maps a number to a text -

Ember.Handlebars.helper('getStatusText', function (value, options) {
    switch(value) {
        case 1: return "Fresh";
            break;
        case 2: return "Callback";
            break;
        default: return "Unable to get Status";
    }
});

I am able to use the helper in the view by using {{getStatusText 1}}

But how do I use the helper in an action inside an ObjectController ?

Test.DealController = Ember.ObjectController.extend({

    selectedStatusType: null,
    statusList: ["Fresh","Callback"],

    actions: {
        updateStatus: function(deal) {
// How do I call the handlebars helper here ?
            console.log({{getStatusText 1}});
        }
    },

});

this obviously does not work.

What are the other ways ??

For better understanding, here is the jsbin


Solution

  • Pull the logic out of the helper, making it available to be called both by the helper, and by non handlebars helper items alike. Parsing it into handlebars template and evaluating it is over complicating it.

    Where you put it is up to you, you could namespace it to your app, or just create it as a function that lives with your helper.

    function getStatusText(value){
        switch(value) {
            case 1: return "Fresh";
                break;
            case 2: return "Callback";
                break;
            default: return "Unable to get Status";
        }
    }
    
    Ember.Handlebars.helper('getStatusText', function (value, options) {
      return getStatusText(value);
    });
    

    http://emberjs.jsbin.com/cenep/1/edit