Search code examples
backbone.jsradio-buttonmarionette

Marionette ItemView and radio Buttons


I have data being returned from a server with a status flag. And on each ItemView I have some radio Buttons as follows:

<td><input type='radio' name='<%- id %>-typeRecipe' value='0'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' value='2'></td> 
<td><input type='radio' name='<%- id %>-typeRecipe' value='1'></td>

As each ItemView is being created I want to check if the status returned by the server is the same value as the input value ie either 0,1, or 2 and if it is set that element to selected.

Recipe = Marionette.ItemView.extend({
   ui: {
     comm: 'input[type=radio]'
},

onBeforeRender: function () {
      for (var i = 0; i < this.ui.comm.length; i++) {
        if(parseInt(this.ui.comm[i].value, 10) === this.model.get('status')) {
          this.ui.comm[i].$el.prop('selected')
        }
      }
    }

However, when I view the interface none of the radio buttons have a check in them.

When I debug the code I can see that the line this.ui.comm[i].$el.prop('selected) is being executed so I'm wondering why doesn't it display set the element to selected? BTW I tried using that function on the onRender event also but the same result


Solution

  • I disagree with your approach, instead of having a onBeforeRender function whose whole function is to check the "state" and set it to checked. I would move that "logic" to the template and not have it handled in the view.

    Your template would look something like:

    <td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '0') { %>checked='checked'<% } %>value='0'></td> 
    <td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '2') { %>checked='checked'<% } %>value='2'></td> 
    <td><input type='radio' name='<%- id %>-typeRecipe' <% if (status == '1') { %>checked='checked'<% } %>value='1'></td>
    

    and finally your render'er?? lol. would just look something like:

    this.$el.html(this.template(this.model.toJSON()));
    

    This again is "my opinion" and you can handle it as you see fit, but i like it because that sort of mundane logic clutters the views and just leaves the person behind you reading more code than he/she has too. And ... i think this approach is more "elegant" because that loop you have going on can be avoided completely.