Skip to content

Instantly share code, notes, and snippets.

@beebole
Created December 17, 2021 16:25
Show Gist options
  • Save beebole/95d440dca39f831817d90f73904ade8b to your computer and use it in GitHub Desktop.
Save beebole/95d440dca39f831817d90f73904ade8b to your computer and use it in GitHub Desktop.
import { html } from 'lit';
import { makeObservable, observable, action } from "mobx"
import { MobxLitElement } from '@adobe/lit-mobx';
// create a mobx observable
class Counter {
count = 0;
increment() {
this.count++;
}
constructor(count) {
makeObservable(this, {
count: observable,
increment: action
})
this.count = count
}
}
// create instance that can be shared across components
const counter = new Counter(0);
// create a new custom element, and use the base MobxLitElement class
// alternatively you can use the MobxReactionUpdate mixin, e.g. `class MyElement extends MobxReactionUpdate(LitElement)`
class mobxCounter extends MobxLitElement {
counter = counter
// any observables accessed in the render method will now trigger an update
render() {
return html`
Count is ${this.counter.count}
<br />
<button @click=${this.incrementCount}>Add</button>
`;
}
firstUpdated() {
// you can update in first updated
this.counter.increment(); // value is now 1
}
incrementCount() {
// and you can trigger change in event callbacks
this.counter.increment(); // value is now n + 1
}
}
customElements.define('mobx-counter', mobxCounter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment