Skip to content

Instantly share code, notes, and snippets.

@NullVoxPopuli
Last active July 25, 2021 16:25
Show Gist options
  • Save NullVoxPopuli/007ed696d4b92b7736a5a972abd72802 to your computer and use it in GitHub Desktop.
Save NullVoxPopuli/007ed696d4b92b7736a5a972abd72802 to your computer and use it in GitHub Desktop.
Each Behavior -- Removal
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
export default class ApplicationController extends Controller {
@tracked records = freshArray();
@action addFirst() {
log('add:first, expect one each log');
this.records = [{ id: this.records.length + 1 }, ...this.records ];
}
@action addLast() {
log('add:last, expect one each log');
this.records = [...this.records, { id: this.records.length + 1 } ];
}
@action addMiddle() {
log('add:middle, expect one each log');
let [first, second, ...rest] = this.records;
this.records = [first, second, { id: this.records.length + 1 }, ...rest ];
}
@action removeFirst() {
log('first removed, expect no each logs');
let [,...rest] = this.records;
this.records = rest;
}
@action removeLast() {
log('last removed, expect no each logs');
let copy = [...this.records];
copy.pop();
this.records = copy;
}
@action removeMiddle() {
log('middle removed, expect no each logs');
let [,middle, ...rest] = this.records;
this.records = this.records.filter(record => record !== middle);
}
@action reset() {
log('this.records has been reset, expect for logs');
this.records = freshArray();
}
}
function freshArray() {
return [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4} ];
}
function log(msg) {
let dashes = '-------';
console.log(`${dashes} ${msg} ${dashes}`);
}
{{#each this.records as |record|}}
{{record.id}}
{{log record.id}}
{{/each}}
<hr>
<p>
Open the brower console and watch when the log in the each loop runs
</p>
<button {{on 'click' this.removeFirst}}>Remove First</button>
<button {{on 'click' this.removeMiddle}}>Remove Middle</button>
<button {{on 'click' this.removeLast}}>Remove Last</button>
<br>
<button {{on 'click' this.addFirst}}>Add First</button>
<button {{on 'click' this.addMiddle}}>Add Middle</button>
<button {{on 'click' this.addLast}}>Add Last</button>
<br>
<br>
<button {{on 'click' this.reset}}>Reset</button>
{
"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