How do I create a component that generates Radio-b

2019-03-28 09:49发布

问题:

Can I and should i pass arrays to components in ember?

For example if I wanted to template something that renders a couple of radiobuttons with labels:

<label for="media">Media</label><input type="radio" name="entry.1602323871" value="media" id="media" />
<label for="guest">Guest</label><input type="radio" name="entry.1602323871" value="guest" id="guest" />

Could I somehow pass an array with this content and loop through it.

Media, media
Guest, guest

回答1:

Yeah, You can pass anything to components. Just a try to the radio-buttons

//Basic radio Component
App.RadioButton = Ember.Component.extend({
  tagName : "input",
  type : "radio",
  attributeBindings : [ "name", "type", "value", "checked:checked" ],
  click : function() {
    this.set("selection", this.$().val());
  },
  checked : function() {
    return this.get("value") === this.get("selection");
  }.property('selection')
});
Em.Handlebars.helper('radio-button',App.RadioButton);

Updated (component name should be dasherized)

Working Radio Demo



回答2:

It's now a tiny bit easier to get radio-buttons into your project (if you're using ember-cli) by using the ember-radio-buttons addon

Install:

npm install ember-radio-buttons --save-dev

Usage:

{{radio-button value='one' checked=selectedNumber}}
{{radio-button value='two' checked=selectedNumber}}


回答3:

Upped @selva-G's answer.

I found that using the ButtonGroup Component from Bootstrap-for-Ember is actually cleaner. Here's what I've done:

In my view's template:

<script type="text/x-handlebars" data-template-name="myview">
    {{bs-btn-group contentBinding="things" selectedBinding="selectedThing"}}
</script>

In that view's controller (which doesn't necessarily need to be an ArrayController, rather can be a generic Ember Controller):

App.MyviewController = Ember.ArrayController.extend({
    things: [
        Ember.Object.create({value: 'first', title: 'First Thing'}),
        Ember.Object.create({value: 'second', title: 'Second Thing'}),
        Ember.Object.create({value: 'third', title: 'Third Thing'})
    ],
    selectedThing: 'second'
    selection: function() {
        console.log(this.get('selectedThing');
    }.observes('selectedThing')
});