Skip to content

Instantly share code, notes, and snippets.

@optikalefx
Last active July 28, 2020 12:31
Show Gist options
  • Save optikalefx/927a61891fd555a09556685dbe6483ec to your computer and use it in GitHub Desktop.
Save optikalefx/927a61891fd555a09556685dbe6483ec to your computer and use it in GitHub Desktop.
toggle-buttons
import Controller from '@ember/controller';
import { action } from '@ember/object';
export default class ApplicationController extends Controller {
appName = 'Ember Twiddle';
currentTab = "second";
@action
finalChoice(choiceText, choiceButton) {
console.log('final choice', choiceText);
}
}
import { helper } from '@ember/component/helper';
export default helper(function eq(params/*, hash*/) {
return params[0] === params[1];
});
body {
margin: 12px 16px;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12pt;
}
.toggle-buttons {
display: flex;
}
.toggle-buttons button.selected {
color: green;
}
<ToggleButtons @onChoose={{this.finalChoice}} as |Tbutton|>
<Tbutton @text="First Option" @selected={{eq this.currentTab "first"}}/>
<Tbutton @text="Second button" @selected={{eq this.currentTab "second"}}/>
</ToggleButtons>
import Component from '@ember/component';
import { action } from '@ember/object';
export default Component.extend({
selected: false,
text: '',
// register the children with the parent
didInsertElement() {
if (this.onInsert) this.onInsert(this);
},
// when we click, set selected and fire a selection
btnClick: action(function() {
this.set('selected', true);
if (this.onSelect) this.onSelect(this.text, this);
})
});
<button {{on "click" this.btnClick}} class={{if this.selected "selected"}}>
{{this.text}}
</button>
import Component from '@ember/component';
import { action } from '@ember/object';
export default Component.extend({
// holds all the child buttons
buttons: [],
// register the child with the parent
// we need this so we can reset the other children
childAdded: action(function(child) {
this.buttons.pushObject(child);
}),
// when the parent has a selection
onSelect: action(function(text, selectedButton) {
const otherButtons = this.buttons.filter(b => b !== selectedButton);
otherButtons.setEach('selected', false);
if (this.onChoose) this.onChoose(text, selectedButton);
})
});
<div class="toggle-buttons">
{{yield (component 'toggle-button-button' onSelect=this.onSelect onInsert=this.childAdded)}}
</div>
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"@glimmer/component": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment