Skip to content

Instantly share code, notes, and snippets.

@les2
Forked from amk221/components.my-component\.js
Last active June 30, 2023 18:29
Show Gist options
  • Save les2/b3a7b30d741030e64c1f866700cd4648 to your computer and use it in GitHub Desktop.
Save les2/b3a7b30d741030e64c1f866700cd4648 to your computer and use it in GitHub Desktop.
didUpdateAttrs replacement
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export default class extends Component {
@tracked value;
constructor() {
super(...arguments);
this.value = this.args.value;
if (this.args.registerAPI) {
this.args.registerAPI(this.publicAPI);
}
}
get publicAPI() {
return {
updateValue: (newValue) => {
this.value = newValue;
}
};
}
@action
changeValue() {
this.value++;
this.args.onChangeValue(this.value);
}
}
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
export default class ApplicationController extends Controller {
@tracked value = 1;
api;
@action
changeValue() {
this.value++;
this.api.updateValue(this.value);
}
@action
handleChangeValue(value) {
// Controller can respond to component giving it a new value
// but not vice versa :(
this.value = value;
}
@action
registerAPI(api) {
this.api = api;
}
}
.my-component {
border: 1px solid red;
padding: 10px;
margin: 10px;
}
<p>
State is intentionally stored inside both the component and the controller.
The component can change the value by itself.
Should the controller give the component a new value
(by clicking "Change value outside component")
then the component should be able to read that in.
This used to be possible with didUpdateAttrs.
</p>
External value: {{this.value}}<br />
<br />
<button type="button" {{on "click" this.changeValue}}>
Change value outside component
</button>
<MyComponent
@value={{this.value}}
@onChangeValue={{this.handleChangeValue}}
@registerAPI={{this.registerAPI}}
/>
<div class="my-component" {{!did-update @value}}>
Internal value: {{this.value}}<br />
<br />
<button type="button" {{on "click" this.changeValue}}>
Change value inside component
</button>
</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