Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 794
Ajey Avatar asked Aug 03 '14 18:08

Ajey


2 Answers

With ember-cli it can be done like this:

// helpers/foo.js
export function foo(params) {
    return params;
}
export default Ember.Helper.helper(foo);

Helper foo exports a function (containing the helper logic) and the function wrapped in an Ember helper (for use in a template).

// helpers/bar.js
import { foo } from '<project>/helpers/foo';
export function bar(params) {
    return foo(params);
}
export default Ember.Helper.helper(bar);

Helper bar imports the helper function from foo and uses it in it's own template helper.

like image 158
Jan Avatar answered Oct 13 '22 20:10

Jan


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

like image 24
Kingpin2k Avatar answered Oct 13 '22 22:10

Kingpin2k