今回は、Reactや他のフレームワークを使わず、WebComponentsのCustomElementsだけでFluxのコンポーネントを実装する方法を書いていく。
(初めに、今回のサンプルで示すコードは全てGitHubで見れる。サンプルはサンプルページで見れる(polyfillを使ってないのでChromeが必要)。そして、今回のFlux実装は10分で実装するFluxを参考に書いているので、そちらも参照してもらいたい。)
さて、Fluxのコンポーネントの役割には、状態(state)が変更されたらViewを更新するというのがある。これをどのようにCustomElementsで行えるか。
CustomElementsにはattributeChangedCallbackというメソッドがある。これは、attributeが変更された時、それがobservedAttributesで監視しているattributeであった場合に呼ばれるメソッドだ。これを利用する方法もあるかもしれないが、attributeには文字列しか指定できないため、文字列以外の状態(state)の変更を受け取るには難しい。
ただ、この一連の流れは応用できそうだ。attributeが変更された時に、attributeChangedCallbackが呼ばれるなら、状態(state)が変更された時に、stateChangedCallbackというメソッドを呼ぶようにしたらどうだろうか。setStateでstateを変更して、observedStateで監視対象のstateを指定して、監視対象のstateが変更されたらstateChangedCallbackを呼ぶという流れだ。
import dispatcher from './dispatcher'; import action from './action'; import store from './store'; const template = document.createElement('template'); template.innerHTML = ` <span></span> <button type="button">+</button> `; export default class Component extends HTMLElement { constructor() { super(); const content = template.content.cloneNode(true); this.span = content.querySelector('span'); const incrementButton = content.querySelectorAll('button')[0]; incrementButton.addEventListener('click', (e) => { action.countUp(); }); this.appendChild(content); store.on('CHANGE', () => { this.setState({ count: store.count }); //this.setState(store)と書いても問題ない; }); //初期処理; this.setState({ count: store.count }); } setState(state) { if(typeof state !== 'object' || state === null) return; if(typeof this.state !== 'object' || this.state === null) this.state = {}; const oldState = this.state; const newState = this.state = Object.assign({}, this.state, state); if(Array.isArray(this.constructor.observedState) === false) return; if(typeof this.stateChangedCallback !== 'function') return; this.constructor.observedState.forEach((name) => { if(oldState[name] === newState[name]) return; this.stateChangedCallback(name, oldState[name], newState[name]); }); } stateChangedCallback(name, oldValue, newValue) { switch(name) { case 'count': this.span.textContent = newValue; break; } } static get observedState() { return ['count']; } } customElements.define('x-component', Component);
このコードはstoreに変更があると、storeから必要なstateを取得して、setStateを実行している。setStateが実行されると監視対象のstate(この場合’count’)に変更がないか調べる。もし変更があれば、stateChangedCallbackを呼ぶようになっている。stateChangedCallbackで、変更のあったstateに応じてViewを更新する。
このように、コンポーネントに新しいライフサイクルを追加することによって、Fluxのコンポーネントの役割である「状態(state)が変更されたらViewを更新する」を実現できるようになる。
さて、このsetStateメソッドをコンポーネント毎に一々実装していられないので、モジュール化してみる。これをコンポーネントが必要に応じて呼び出すのがいいだろう。npmにもusestateという名で上げてみた。
const map = new WeakMap(); const privates = (object) => { if(! map.has(object)) { map.set(object, {}); } return map.get(object); }; function getState() { return privates(this).state; } function setState(state) { if(typeof state !== 'object' || state === null) return; const that = privates(this); if(typeof that.state !== 'object' || that.state === null) that.state = {}; const oldState = that.state; const newState = that.state = Object.assign({}, that.state, state); if(Array.isArray(this.constructor.observedState) === false) return; if(typeof this.stateChangedCallback !== 'function') return; this.constructor.observedState.forEach((name) => { if(oldState[name] === newState[name]) return; this.stateChangedCallback(name, oldState[name], newState[name]); }); } export default function useState(target) { if(typeof target !== 'function') throw new TypeError(); target.prototype.getState = getState; target.prototype.setState = setState; return target; }
これを以下のように呼び出すと、コンポーネントはsetStateメソッドを使えるようになる。
import useState from './useState'; class Component extends HTMLElement { /* ... * /} export default useState(Component)
また、現在ES Proposal stage2のDecoratorsを使って書くこともできる。(要babel)
import useState from './useState'; @useState export default class Component extends HTMLElement { /* ... */}
さて、先程例示した、Component.jsは最終的に以下のようなコードになった。実際に先程のコードのように書いてしまうとメモリリークを起こしてしまう可能性があるためその点も含め若干変わっている
import dispatcher from './dispatcher'; import action from './action'; import store from './store'; import useState from './useState'; const template = document.createElement('template'); template.innerHTML = ` <span></span> <button type="button">+</button> `; class Component extends HTMLElement { constructor() { super(); this.handleStoreChange = this.handleStoreChange.bind(this); const content = template.content.cloneNode(true); this.span = content.querySelector('span'); const incrementButton = content.querySelectorAll('button')[0]; incrementButton.addEventListener('click', (e) => { action.countUp(); }); this.appendChild(content); } handleStoreChange() { this.setState({ count: store.count }); } connectedCallback() { store.on('CHANGE', this.handleStoreChange); //初期処理 this.handleStoreChange(); } disconnectedCallback() { store.removeListener('CHANGE', this.handleStoreChange); } stateChangedCallback(name, oldValue, newValue) { switch(name) { case 'count': this.span.textContent = newValue; break; } } static get observedState() { return ['count']; } } customElements.define('x-component', Component); export default useState(Component)
dispatcherやstoreやactionの実装も載せておく。 (eventsモジュールはNode.jsの標準モジュール。中身はEventEmitter)
import Emitter from 'events'; export default new Emitter();
import dispatcher from './dispatcher'; export default { countUp() { dispatcher.emit('countUp'); }, }
import Emitter from 'events'; import dispatcher from './dispatcher'; class Store extends Emitter { constructor(dispatcher) { super(); this.count = 0; dispatcher.on('countUp', {}); } onCountUp() { this.count++; this.emit('CHANGE'); } } export default new Store(dispatcher);このコンポーネントを例えば以下のように描画してやれば、サンプルページ(要chrome)のようになる
import Component from './Component'; const component = new Component(); document.body.appendChild(component);
これで。Fluxの一連の流れをフレームワークを使わなくても実現できそうだ。これは、データーバインディングの方法を例示したに過ぎないからCustomElementsに限らず使える。ただ、今回の肝は、監視対象のattributeが変更されたらattributeChangedCallbackが呼ばれるというCustomElementsのライフサイクルに習って、監視対象のstateが変更されたらstateChangedCallbackを呼ぶというライフサイクルを追加したことにある。だから、CustomElementsとは親和性が高く、理解しやすいだろう。
しかし、上の方法はある種オレオレフレームワークだと思う方がいるかもしれない。もし、この方法が気に入らないのであれば、個別にsetterを用意して状態をまとめてではなく個別に監視することも出来るだろう。Componentが必要とするstateが多くなれば少し冗長な書き方になってしまうが、全く標準な方法で実装ができる。useStateを使ったComponentとの違いを見比べてほしい。
import dispatcher from './dispatcher'; import action from './action'; import store from './store'; const template = document.createElement('template'); template.innerHTML = ` <span></span> <button type="button">+</button> `; class Component extends HTMLElement { constructor() { super(); this.handleStoreChange = this.handleStoreChange.bind(this); const content = template.content.cloneNode(true); this.span = content.querySelector('span'); const incrementButton = content.querySelectorAll('button')[0]; incrementButton.addEventListener('click', (e) => { action.countUp(); }); this.appendChild(content); } set count(value) { if(value === this._count) return; //変更がないなら何もしない this._count = value; this.span.textContent = value; } handleStoreChange() { this.count = store.count; } connectedCallback() { store.on('CHANGE', this.handleStoreChange); //初期処理 this.handleStoreChange(); } disconnectedCallback() { store.removeListener('CHANGE', this.handleStoreChange); } } customElements.define('x-component', Component); export default Component
これらの実装は、状態(state)を監視しているので、変更のあった部分だけDOM操作するのを助ける。そして、これは生DOMを操作して開発する時の方法である。だから、今流行りの仮想DOMと比べて面倒くささもあるだろう。例えば、状態(state)の差分を測るのは自分でやらなければならない。それにしても、フレームワークに振り回されず標準に近い方法で開発していくメリットは大きいと思う。ぜひ興味のある方はこの方法を試してほしい。
先程のusestateは npm i -S usestate
でインストールできる。