0.2.2 • Published 5 years ago

obsjs v0.2.2

Weekly downloads
2
License
ISC
Repository
github
Last release
5 years ago

OBSJS

Yet another Observer Pattern library for Javascript! This library provides a simple Observer Pattern that you would have seen before, but also brings some new features that you would haven't seen before.

Installation

npm install obsjs --save

Usage

Every Observer Patter implementations will come with two main things: Observer and Subject. ObsJS also comes with both of them but instead of Observer, it has Obs.

Obs and Subject are two main things of the library.

Creating Subject and Obs

const obsjs = require("obsjs");
//import { Subject, Obs } from "obsjs";

let sub = new obsjs.Subject();
let obs1 = new obsjs.Obs("double", val => val * 2);
let obs2 = new obsjs.Obs("square", val => val * val);

The Obs constructor takes two parameters: the name of the Obs and the action that the Obs will do when the Subject notifies it, default is a dump function () => {}. You can't change the name of the Obs but you can change the action.

Register Subject

To make the Subject can notify the Obs, we register the Obs with the Subject.

obs1.register(sub);
obs2.register(sub, ["pow"])

The register method takes two parameters: the Obs and the array of groups that the Obs will be in, default is ["all"]. The Subject will add the Obs to the group which is registered.

Note: Having Obses with the same name in the same group will throw an error!

Notify Obs

The Subject can notify to its Obs through notify method.

sub.notify([], 2);
sub.notify(["pow"], 3);

The method take two parameters: the array of groups that will be notified, default is ["all"], and the data that will be passed to the Obs action, default is null.

Every Obses in all group are always notified regardless of the notified groups, even the empty array is passed in.

The notify method returns the results of the actions of the Obses, you can store the return value for further use. The return value is the collection of the key-value pairs, which key is the name of the Obs and the value is the result of the action.

console.log(sub.notify([], 2)); //{ double: 4 }
console.log(sub.notify(["pow"], 3)); //{ double: 6, square: 9 }

Unregister

When the Obs no longer "keep in touch" with the Subject, you can unregister it.

obs1.unregister(sub);

The method takes only one parameter: the Subject that the Obses registered.

Change the action of the Obs

To change the action of the Obs, use changeAction method, set its action to new action.

/* This method will be depecrated soon! */
obs2.changeAction(val => `Square: ${val * val}`);
/******************************************/

obs2.action = val => `Square: ${val * val}`; // Use this instead!
console.log(sub.notify(["pow"], 3)); // { square: "Square: 9" }
// No "double" because we unregistered it!

Find the Obs

The find method will return the array of groups that the Obs is in or an empty array if the Obs doesn't register the Subject.

sub.find(obs2); // ["pow"]

This method will take only one parameter: the Obs object or the Obs name that you want to find.

Or you can check if the Obs has registered the Subject.

obs1.hasRegistered(sub); // true

The hasRegistered method takes the Subject object as the parameter.

Using with ReactJS

You can use this library in ReactJS, example:

// The subject component
const CompA = () => {
	const [subject] = useState(new Subject());
	const [text, changeText] = useState("Nothing");

	const onGetText = () => {
		const result = subject.notify();
		changeText(result.count);
	};

	return (
		<div>
			<button onClick={() => onGetText()}>Get count!</button>
			<CompB name="count" subject={subject} />
			<div>{text}</div>
		</div>
	)
};

//The obs component
const CompB = ({ name, subject }) => {
	const [obs] = useState(new Obs(name));
	const [count, setCount] = useState(0);

	useEffect(() => {
		if (subject) {
			obs.register(subject);
		}

		//Remember to unregister when the component is going to unmount
		return () => {
			if (subject) {
				obs.unregister(subject);
			}
		}
	}, [])

	useEffect(() => {
		//You must set the action everytimes the state is changed
		obs.action = () => count * 2;
	}, [count]);

	return ( 
		<button onClick={() => setCount(count + 1)}>
			Increase!
		</button>
	);
}

Test

npm run test

Future features

  • Allow the Obs has different actions when in different groups.
  • Async Obs and Async Subject

Author

Phan Dung Tri

Email: phandungtri4work@gmail.com

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.2

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago