문제

I understand that to bind a ractive variable to a radio-button, the easiest way is to have

<input type="radio" name="{{myVar}}" value="1" checked>

in the template, but the curly brackets on the name persist into the html. Is there a clever way to get it to output

<input type="radio" name="myVar" value="1" checked>

in the html, so I don't have to alter the form-handling? I've tried some logic along the lines of

<input type="radio" name="myVar" value="1" {{#myVar==1}}checked{{/myVar==1}}

but that doesn't bind.

Also, less importantly, is there a way to bind it as a numeric value, as if I have

data:{myVar:1}

Then the button doesn't get checked?

도움이 되었습니까?

해결책

Ractive adds the curly braces to input names to guard against the (highly unlikely) possibility of a conflict between name='{{myVar}}' and name='myVar' - no other reason. The binding is created when the element is rendered; what the name becomes after that is irrelevant.

So although there's no way to prevent the curly braces being added in the first place, you can certainly change them afterwards:

ractive.findAll('input[type="radio"]').forEach( function(input) {
  input.name = input.name.replace('{{','').replace('}}','');
});

If you were creating a component with Ractive.extend() this could be part of the init() method, for example.

It shouldn't have a problem with numeric values, at least as of the last released version (0.3.9) and current development version (0.4.0). See this fiddle for an example: http://jsfiddle.net/rich_harris/7qQZ8/

다른 팁

Short answer: I don't think it's possible to do what you want.

Ractive handles radio buttons differently than simple HTML markup. It assumes that you're going to want to retrieve which radio button is set using a simple variable, and it relies on the name attribute to do that. Specifically, it expects you to set the name attribute to the same specific variable (e.g. "{{myVar}}") in all radio buttons in a group. It will then automatically set that variable to the value attribute of whichever individual radio button is selected.

For example, if you have the following code:

    <label><input type='radio' name='{{myVar}}' value='1' checked> 1</label>
    <label><input type='radio' name='{{myVar}}' value='2'        > 2</label>
    <label><input type='radio' name='{{myVar}}' value='3'        > 3</label>
    <p>The selected value is {{myVar}}.</p>

Then Ractive will automatically update the <p> with information on whatever radio button is selected.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top