@alcadica/signal
v1.0.3
Published
Signals for typescript
Downloads
43
Readme
@alcadica/signal
A signal is basically a function with a subscription system bound to it.
Install
npm i --save @alcadica/signal
Examples
A real-life example:
// file CounterAspect.ts
import signal from '@alcadica/signal';
export const increment: signal = signal();
export const dispose: signal = signal();
export const stateDidChange: signal = signal();
export const state = {
counter: 0
}
export default {
dispose,
increment,
state,
stateDidChange
}
increment.connect(() => {
state.counter++;
});
// my-component.tsx
import * as React from 'react';
import CounterAspect from './CounterAspect';
export class MyComponent extends React.Component<any, any> {
public state: any = CounterAspect.state;
public componentDidMount(): void {
const signalid = CounterAspect.stateDidChange.connect((key, value) => this.setState({ [key]: value }));
CounterAspect.dispose.connect(() => CounterAspect.stateDidChange.disconnect(signalid));
}
public componentWillUnmount(): void {
CounterAspect.dispose();
}
public render(): JSX.Element {
return (
<div onClick={CounterAspect.increment}>{CounterAspect.state.counter}</div>
)
}
}
A signal subscription can also be consumed only once
import signal from '@alcadica/signal';
const foo = { bar: 0 }
const baz = signal<[number]>();
baz.connectOnce(arg => foo.bar = foo.bar + arg);
baz(1) // foo.bar is 1
baz(1) // foo.bar is still 1
baz(1) // foo.bar is still 1 again