Define array inside template for handlebars/ember?

浪子不回头ぞ 提交于 2019-12-10 10:15:14

问题


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' 

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/20327796/define-array-inside-template-for-handlebars-ember

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!