0
votes

I'm trying to build a new conditional helper for my Ember application. Is important mention that I'm using Ember 1.10.1 that uses Handlebars 2.0 and I can't upgrade it, would be great solving the problem with this version of Ember. Before writing here I tried different solutions and debugged the Ember code a lot, I'm near to the solution but probably I'm missing something.

First of all, I tried with the following approach reading the Handlebar documentation:

Ember.Handlebars.registerHelper('helperName', function(conditional, options) {
    if(conditional) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

And here the template:

{{#helperName booleanCondition}}
    print true
{{else}}
    print false
{{/helperName}}

Everything worked fine calling the fn function but the inversion function (used to render the template of the else branch) was actually an object instead of a function.

Then I started debugging the Ember code and I tried to follow the same approach that Ember uses with the if helper, so I ended up with the following:

Ember.Handlebars.registerHelper('helperName', function(condition, options) {

    var permission = Ember.Object.extend({
        can: Ember.computed(function() {
            return condition;
        })
    }).create();

    Ember.Handlebars.helpers.boundIf.helperFunction.call(this, ["can"], permission, options, options.data.buffer);
});

can is the property bound to the if, used to change the template if the property changes, since we are using the boundIf version of the if (that does what I just said).

The problem of this solution, that imho could be the nearest to be correct, is that the property is not computed correctly and the helper prints always the false value. I debugged really a lot without making it working, so any help would be very appreciated and I hope this could be useful for someone else as well.

2

2 Answers

1
votes

If what you're trying to do is build a conditional approach that supports authorization questions, you should take a look at ember-can. It is an Ember-CLI addon (whereas it looks like you are doing globals) but older versions worked with Ember 1.10. You should be able to reference what they do there and pull it in on your setup

0
votes

The good news is you are on Ember 1.10! This means you have subexpressions. And its simple to create a bound non-block helper:

Ember.HTMLBars._registerHelper('foo', function(bar) {
  return bar == 'bar';
});

To use it as a block helper combine it with the {{#if}} helper:

{{#if (foo model)}}
  in if
{{else}}
  in else
{{/if}}