How do I create a component that generates Radio-buttons in Ember.js?

空扰寡人 提交于 2020-01-01 05:21:22

问题


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')
});


来源:https://stackoverflow.com/questions/20268764/how-do-i-create-a-component-that-generates-radio-buttons-in-ember-js

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