Skip to content

Instantly share code, notes, and snippets.

@MrChocolatine
Last active December 16, 2021 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrChocolatine/31cfeb769ca20a99f8fc1d9c09e2c794 to your computer and use it in GitHub Desktop.
Save MrChocolatine/31cfeb769ca20a99f8fc1d9c09e2c794 to your computer and use it in GitHub Desktop.
Ember.js getters/setters
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { tracked } from '@glimmer/tracking';
const DEFAULT_A = [ 'default_a' ];
const DEFAULT_B = [ 'default_b' ];
export default class AppController extends Controller {
@tracked _prop_A = DEFAULT_A.slice();
@tracked _prop_B = DEFAULT_B.slice();
get prop_A() {
return this._prop_A;
}
set prop_A(value) {
this._prop_A = value;
}
get prop_B() {
return this._prop_B;
}
set prop_B(value) {
if (value === undefined) {
this._prop_B = DEFAULT_B.slice();
} else {
this._prop_B = [ `new value b${value}` ];
this.prop_A = [ ...this.prop_A, value ];
}
}
@action update_A(shouldAdd) {
const arr = this.prop_A.slice();
if (shouldAdd === true) {
this.prop_A = [ ...arr, arr.length ];
} else if (shouldAdd === false) {
this.prop_A = arr.slice(0, -1);
} else {
this.prop_A = DEFAULT_A.slice();
}
}
@action update_B(value) {
this.prop_B = value;
}
}
<button {{on "click" (fn this.update_A true)}}>
Add to `prop_A`
</button>
<button {{on "click" (fn this.update_A false)}}>
Remove from `prop_A`
</button>
<button {{on "click" (fn this.update_A undefined)}}>
Reset `prop_A`
</button>
<br>
<br>
<button {{on "click" (fn this.update_B 1)}}>
Set `prop_B` with 1
</button>
<button {{on "click" (fn this.update_B 2)}}>
Set `prop_B` with 2
</button>
<button {{on "click" (fn this.update_B undefined)}}>
Reset `prop_B`
</button>
<hr>
this.prop_A => {{this.prop_A}}
<br>
<br>
this.prop_B => {{this.prop_B}}
{
"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",
"@glimmer/tracking": "1.0.0"
},
"addons": {
"@glimmer/component": "1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment