26
loading...
This website collects cookies to deliver better user experience
postMessage()
method, and respond to messages via the onmessage
event handler.import { createAppState } from 'https://cdn.skypack.dev/ficusjs@3'
const store = createAppState('worker.test', {
initialState: {
text: 'hello world'
},
setText (text) {
this.state.text = text
}
})
worker.js
:// import the web worker friendly app state creator function
importScripts('https://unpkg.com/@ficusjs/[email protected]/dist/worker-app-state.iife.js')
// Initialize the store using the ficusjs.createAppState function
const store = globalThis.ficusjs.createAppState({
initialState: {
text: 'hello world'
},
setText (text) {
this.state.text = text
}
})
// a function for communicating with the UI thread
function postState () {
globalThis.postMessage(Object.assign({}, store.state))
}
// subscribe to store changes
store.subscribe(postState)
// listen for actions to invoke in the store
globalThis.onmessage = function (e) {
const { actionName, payload } = e.data
store[actionName](payload)
}
// post the initial state to any components
postState()
withWorkerStore
function to extend the component with the worker.import { createCustomElement, withWorkerStore } from 'https://cdn.skypack.dev/ficusjs@3'
import { html, renderer } from 'https://cdn.skypack.dev/@ficusjs/renderers@3/htm'
createCustomElement('example-worker-component',
withWorkerStore(new Worker('./worker.js'), {
renderer,
onButtonClick () {
this.dispatch('setText', 'This is a test')
},
render () {
return html`
<section>
<p>${this.state ? html`${this.state.text}` : ''}</p>
<button type="button" onclick="${this.onButtonClick}">Dispatch worker action</button>
</section>
`
}
})
)
withWorkerStore
function provides a this.state
property within the component as well as a this.dispatch()
method for invoking store actions.26