Skip to content

Instantly share code, notes, and snippets.

@akfernun
Last active January 4, 2022 12:55
Show Gist options
  • Save akfernun/b69c24fb22daf2cf0ebd71cabe08b425 to your computer and use it in GitHub Desktop.
Save akfernun/b69c24fb22daf2cf0ebd71cabe08b425 to your computer and use it in GitHub Desktop.
Child components
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class extends Component {
get context() {
return JSON.stringify(this.args.machine.machine.context)
}
@action
updateContext() {
this.args.machine
.onTransition((state) => console.log('CHILD STATE: ', state))
.send("UPDATE_CONTEXT")
}
}
import Component from '@glimmer/component';
import { matchesState, useMachine } from 'ember-statecharts';
import { createMachine, assign } from 'xstate'
import { action } from '@ember/object'
import { use } from 'ember-usable';
const childMachine = createMachine({
id: "child-machine",
initial: "idleChild",
states: {
idleChild: {
on: {
UPDATE_CONTEXT: {actions: ['updateContext']},
}
}
}
},
{
actions: {
updateContext: assign({prop1: 'new value'})
}
});
const parentMachine = createMachine({
id: "parent-state-machine",
initial: "idle",
states: {
idle: {
on: { INVOKE_CHILD: "withChildMachine" }
},
withChildMachine: {
invoke: {
id: "child-machine",
src: childMachine,
data: {
prop1: "original value"
}
},
on: {
RESET: "idle"
}
}
}
});
export default class extends Component {
@matchesState('idle') isIdle;
@matchesState('withChildMachine') isShowingChild;
@use statechart = useMachine(parentMachine).onTransition((state) => console.log("PARENT STATE: ", state));
get childMachine() {
return this.statechart.state.children['child-machine'];
}
@action
invokeChild() {
this.statechart.send("INVOKE_CHILD")
}
@action
reset() {
this.statechart.send("RESET")
}
}
import Controller from '@ember/controller';
export default class ApplicationController extends Controller {
appName = 'Ember Twiddle';
}
<ParentMachine />
<br>
<br>
<h2>CHILD MACHINE</h2>
<div>
{{this.context}}
</div>
<button {{on "click" this.updateContext}}>UPDATE CONTEXT WITH NEW VALUE</button>
<h1>Parent Machine</h1>
{{#if this.isIdle}}
<button {{on "click" this.invokeChild }}>Press to invoke child machine</button>
{{else}}
<button {{on "click" this.reset }}>Reset</button>
<ChildMachine @machine={{this.childMachine}} />
{{/if}}
{
"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",
"ember-statecharts": "0.13.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment