0
votes

The problem stems from the inability to do comparisons in the template:

{{#if model.input.type == 'select'}}

The option around this, that I'm aware of so far, is to use a custom Handlebars helper. This would allow me to loop through the model and build out the HTML, but this doesn't allow me to bind attributes, plus just it seems like too much work.

1. Can't bind attributes, and I don't want to build out HTML with a JS string.   

Handlebars.registerHelper('formBuilder', function()
{
    var html_string = '';

    for(var q=0; q<this.content.questions.length; q++)
    {
        if(this.content.questions[q].type.match(/select/i))
             { /* build out html with model propeties */ }

        if(this.content.questions[q].type.match(/checkbox|radio/i))
             { /* build out html with model propeties */ }

    }
    return new HandleBars.SafeString(html_string);
}

A better option would be if I could track the index in my helper, and return a Handlebars expression, all without breaking the template's loop:

        2. Can't pass in loop index or return expressions.

        {{#each question in model.questions}}
            {{#formBuilder parent.index this}}
                /* uses @index to iterate through its children and return a Handlebars 
                   expressions for either select or checkbox html */
            {{/formBuilder}}
        {{/each}}

...and the formBuilder helper would look something like this:

Handlebars.registerHelper('formBuilder', function(q_index, model)
{
    if(model[q_index].type == 'select')
    {
        return Handlebars.compile({{select action 'myAction' type='model[q_index].type'}});
    }

    if(model[q_index].type.match(/checkbox|radio/i))
    {
        return Handlebars.compile({{input action 'myAction' type='model[q_index].type'}});
    }

});

wich would return controll to the outer loop.

How is this problem solved in Ember?

1

1 Answers

0
votes

Looking at what you are trying to achieve more closely, I would suggest you use a view instead of a handlebars helper to create either a checkbox or a select field. The way you would do that would be

{{#each question in questions}}
  {{view QuestionView contentBinding=this}}
{{/each}}

and in your questionView,

 App.QuestionView = Em.View.extend({

   defaultTemplate: (function() {
      if(this.get('type') === 'select') {
        return Em.Handlebars.compile(//select box string goes here);
      }
      else {
        return Em.Handlebars.compile(//checkbox html);
      }
   })()
 });