Skip to content

Instantly share code, notes, and snippets.

@acknudson
Last active April 19, 2021 23:20
Show Gist options
  • Save acknudson/2cb000537294ac32167c2bdc24bd4998 to your computer and use it in GitHub Desktop.
Save acknudson/2cb000537294ac32167c2bdc24bd4998 to your computer and use it in GitHub Desktop.
arrays are dumb
import Controller from '@ember/controller';
import {action, computed, set} from '@ember/object';
import {A} from '@ember/array';
export default class ApplicationController extends Controller {
appName = 'Ember Twiddle';
numberSelected = 1;
_nameArray = A(['']);
@computed('numberSelected', '_nameArray.[]')
get nameArray() {
const a = this._nameArray;
const lengthDifference = Math.abs(this.numberSelected - a.length);
if (this.numberSelected > a.length) {
// add name slots
for (let i = 0; i < lengthDifference; i++) {
a.push('');
// a.push({ name: '' });
}
} else if (this.numberSelected < a.length) {
// remove name slots
const shorterArray = a.slice(0, this.numberSelected);
return A(shorterArray);
}
return A(a);
}
set nameArray({value, index}) {
set(this, `_nameArray.${index}`, value);
}
@action
selected(event) {
this.set('numberSelected', parseInt(event.target.value));
}
@action newValue(index, event) {
console.log('event', event);
console.log('index', index);
this.set('nameArray', {value: event.target.value, index})
}
}
<h1>Welcome to {{this.appName}}</h1>
<br>
<br>
<p>{{this.numberSelected}}</p>
<select onchange={{action "selected"}}>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<br><br><br>
{{#each this.nameArray as |name index|}}
name: {{name}} <br>
<input value={{name}} oninput={{action "newValue" index}} />
<br>
{{/each}}
<br>
<br>
Hidden values <br>
{{#each this._nameArray as |name|}}
name: {{name}} <br>
<br>
{{/each}}
{
"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