A class that allows adding easy subscription and notification abilities by extending it
npm
npm install @ouroboros/subscribe
To add subscription and notification to your class it's as easy as extending it from Subscribe
import Subscribe from '@ouroboros/subscribe';
export default class MyClass extends Subscribe {
// Constructor
constructor() {
super('Hello, World!');
}
// do class stuff
}
MyForm is passed an instance of MyClass via props.my
import React from 'react';
export default function MyForm(props) {
return (
<button onClick={props.my.set('Goodbye')}>
Say Goodbye
</button>
);
}
MyComponent subscribes to changes to oMy
and adds each one it's notified about to the list of messages
import MyClass from './MyClass';
import MyForm from './MyForm';
import React, { useEffect, useState } from 'react';
// Create a new instance of the subscription
const oMy = new MyClass();
// Create a React Component
function MyComponent(props) {
const [ messages, setMessages ] = useState([]);
useEffect(() => {
// Subscribe to MyClass instance
const r = oMy.subscribe(data => {
// Add each new message we are notified about to the end of the list
setMessages(val => [...messages, data]);
})
// Unsubscribe
return () => {
r.unsubscribe();
}
}, []);
return () {
<div>
<MyForm my={o} />
{msgs.map(s =>
<p>{s}</p>
)}
</div>
}
}
In the example, clicking the button a single time would result in
Say Goodbye
Hello, World!
Goodbye
And a second click...
Say Goodbye
Hello, World!
Goodbye
Goodbye