@ouroboros/subscribe
TypeScript icon, indicating that this package has built-in type declarations

1.2.2 • Public • Published

@ouroboros/subscribe

npm version MIT License

A class that allows adding easy subscription and notification abilities by extending it

Installation

npm

npm install @ouroboros/subscribe

Extending Subscribe

To add subscription and notification to your class it's as easy as extending it from Subscribe

MyClass.js
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

MyForm.js
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

MyComponent.js
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

Package Sidebar

Install

npm i @ouroboros/subscribe

Weekly Downloads

4

Version

1.2.2

License

MIT

Unpacked Size

13.7 kB

Total Files

6

Last publish

Collaborators

  • ouroboros