Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bguiz/9964114 to your computer and use it in GitHub Desktop.
Save bguiz/9964114 to your computer and use it in GitHub Desktop.
{{!--
Sample usage in handlebars template
Say you wish to display an undordered list (`<ul>`) of `Foo` models,
and only one of these `Foo`s can be selected as the primary `Foo`.
We bind each `Foo` to a radio button, with the `checked` attribute
of the radio button updating the `primary` attribute of the `Foo` model.
--}}
{{#view App.RadioButtonGroupView name='foo-group'}}
<ul>
{{#each foo in foos}}
<li>
<label>
<span>{{#if foo.primary}}Primary{{/if}}</span>
{{view view.RadioButton checked=foo.primary value=foo.id}}
</label>
<span>{{foo.name}}</span>
</li>
</ul>
{{/view}}
/*global Ember*/
App.RadioButtonView = Ember.View.extend({
attributeBindings: ['name', 'disabled', 'value', 'type', 'checked'],
tagName: 'input',
type: 'radio',
checked: false,
init: function() {
this._super(arguments);
if (this.get('checked')) {
this.set('selected', this.get('value'));
}
},
disabled: Ember.computed.empty('value'),
change: function() {
var isChecked = this.$().prop('checked');
this.set('checked', isChecked);
var selected = this.get('selected');
if (isChecked) {
this.set('selected', this.get('value'));
}
},
otherChanged: function() {
var selected = this.get('selected');
var isChecked = this.get('checked');
var value = this.get('value');
var isCheckedNew = (!Ember.isEmpty(selected) && value === selected);
if (isChecked !== isCheckedNew) {
this.set('checked', isCheckedNew);
}
}.observes('selected')
});
App.RadioButtonGroupView = Ember.View.extend({
tagName: 'div',
attributeBindings: ['name'],
name: Ember.required(),
selected: null,
RadioButton: function() {
return App.RadioButtonView.extend({
radioButtonGroup: this,
selected: Ember.computed.alias('radioButtonGroup.selected'),
name: Ember.computed.alias('radioButtonGroup.name')
});
}.property('name')
});
@ashrafhasson
Copy link

Thanks for the brilliant radio-button-group snippet, I've extracted it into a component for easier code reusability, while I also took the liberty to change small parts of how it works, here :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment