Reputation: 15006
I have a handlebars template in an ember application. It accepts an array. I currently declare the array like this
template:
{{Gd-radio-input content=radioContent value="blue"}}
Javascript:
App.IndexController = Em.Controller.extend({
radioContent: [
{label: 'Red', value: 'red'},
{label: 'Blue', value: 'blue'},
{label: 'Green', value: 'green'},
{label: 'Yellow', value: 'yellow'},
]
});
For my purposes, I would like to define the array inside the template sometimes.
I tried this, but javascrip hates me:
{{Gd-radio-input content="[
{label: 'Red', value: 'red'},
{label: 'Blue', value: 'blue'},
{label: 'Green', value: 'green'},
{label: 'Yellow', value: 'yellow'},
]" value="blue"}}
Errors:
Assertion failed: The value that #each loops over must be an Array. You passed [
{label: 'Red', value: 'red'},
{label: 'Blue', value: 'blue'},
{label: 'Green', value: 'green'},
{label: 'Yellow', value: 'yellow'},
]
Uncaught TypeError: Object [
{label: 'Red', value: 'red'},
{label: 'Blue', value: 'blue'},
{label: 'Green', value: 'green'},
{label: 'Yellow', value: 'yellow'},
] has no method 'addArrayObserver'
Upvotes: 3
Views: 4716
Reputation: 1209
You can generate a helper with ember g helper arr
and then put this code:
{{Gd-radio-input content=(arr
(hash label='Red' value='red')
(hash label='Blue' value='blue')
(hash label='Green' value='green')
(hash label='Yellow' value='yellow')
) value="blue"}}
Explanation: the default helper already returns an array of the parameters. The hash
helper generates the objects. I think the arr
helper should already be in the default Template Helpers, BTW.
p.s.: Thanks to @locks on slack channel
Upvotes: 2
Reputation: 47367
It isn't javascript that hates you, it's handlebars/helper. When you bind the content using the inline string
it doesn't convert it to an array for you.
You could add some sort of contentString value that would convert it back from a string to an array and set it on the content.
{{Gd-radio-input contentString="[
{label: 'Red', value: 'red'},
{label: 'Blue', value: 'blue'},
{label: 'Green', value: 'green'},
{label: 'Yellow', value: 'yellow'},
]" value="blue"}}
GdRadioInput = Em.Componenet.extend({
watchContentString: function(){
var cs = this.get('contentString');
if(cs){
this.set('content', eval(cs));
}
}.on('init')
});
*Note, I'm not really recommending using eval, I'm just lazy.
Upvotes: 0