Introduction
Getting Started
Build your first Comctx connection with the core Comctx quick start flow.
This page follows the core Comctx quick start flow.
Installation
Install comctx in your project:
pnpm install comctxnpm install comctxyarn add comctxbun add comctxDefine the shared service
import { defineProxy } from 'comctx'
class Counter {
public value: number
constructor(initialValue: number = 0) {
this.value = initialValue
}
async getValue() {
return this.value
}
async onChange(callback: (value: number) => void) {
let oldValue = this.value
setInterval(() => {
const newValue = this.value
if (oldValue !== newValue) {
callback(newValue)
oldValue = newValue
}
})
}
async increment() {
return ++this.value
}
async decrement() {
return --this.value
}
}
export const [provideCounter, injectCounter] = defineProxy(() => new Counter(), {
namespace: '__comctx-example__'
})Define the adapter
import type { Adapter, SendMessage, OnMessage } from 'comctx'
export default class CustomAdapter implements Adapter {
// Implement message sending
sendMessage: SendMessage = (message) => {
postMessage(message)
}
// Implement message listener
onMessage: OnMessage = (callback) => {
const handler = (event: MessageEvent) => callback(event.data)
addEventListener('message', handler)
return () => removeEventListener('message', handler)
}
}Create the Provider
import CustomAdapter from 'CustomAdapter'
import { provideCounter } from './shared'
const originCounter = provideCounter(new CustomAdapter())
originCounter.onChange(console.log)originCounter directly references the real Counter instance.
Create the Injector
import CustomAdapter from 'CustomAdapter'
import { injectCounter } from './shared'
const proxyCounter = injectCounter(new CustomAdapter())
// Support for callbacks
proxyCounter.onChange(console.log)
// Transparently call remote methods
await proxyCounter.increment()
const count = await proxyCounter.getValue()proxyCounter is a virtual proxy that forwards requests to the Counter on the Provider side.
Important notes
originCounterandproxyCountershare the sameCounterinstance.- The Injector side cannot directly use
getandset; it must interact withCountervia asynchronous methods. - Callbacks are supported.
- To support operations like
Reflect.has(proxyCounter, 'key'), you can setbackuptotrue. provideCounterandinjectCounterrequire user-defined adapters for different environments that implementonMessageandsendMessage.