gobserver
v2.0.1
Published
A simple implementation of the observer pattern.
Downloads
2
Maintainers
Readme
gobserver
A simple implementation of the observer pattern.
Supported browsers
es5 compliant browsers.
Installing
When using yarn:
yarn add gobserver
When using npm:
npm install gobserver
When using a script tag:
<script src="gobserver.js"></script>
Importing
When using TypeScript or es2015 modules:
import * as gobserver from "gobserver";
// or
import { create } from "gobserver";
When using CommonJS:
const gobserver = require("gobserver");
When using AMD:
define(["gobserver"], (gobserver) => {
// ...
})
Creating
When using JavaScipt:
const observer = gobserver.create();
When using TypeScript:
type Event = {
data: any
};
const observer = gobserver.create<Event>();
When using a custom return value:
type Event = {
data: any
};
class Service {
public readonly onUpdate = gobserver.create<Event, Service>({ returnValue: this });
}
Subscribing / Publishing
Subscribing:
observer.subscribe((evt: Event) => {
console.log(evt.data);
});
Publishing:
observer.publish({ data: 12 });
Registering a handler that is executed only once:
observer.subscribe((evt: Event) => {
console.log(evt.data); // This is executed only once
}, { once: true });
observer.publish({ data: 12 });
observer.publish({ data: 12 });
Registering a handler that is executed under the given context:
const obj = {
value: 1,
foo(evt: Event) {
console.log(this.value + evt.data);
},
};
observer.subscribe(obj.foo, { context: obj })
observer.publish({ data: 2 });
Unsubscribing:
observer.unsubscribe(handler);
Pipe / Unpipe
Pipe events from one observer to another:
const observer = gobserver.create<Event>();
const pipedObserver = gobserver.create<Event>();
pipedObserver.subscribe((evt: Event) => {
console.log(evt.data);
});
observer.pipe(pipedObserver);
observer.publish({ data: 12 });
Unpipe both observers:
observer.unpipe(pipedObserver);
Chaining
gobserver
.create<Event>()
.subscribe((evt: Event) => {
console.log(evt.data);
})
.publish({ data: 12 });
When using a custom return value:
class Service {
public readonly onUpdate = gobserver.create<Event, Service>({ returnValue: this });
public doSomething() {
// ...
return this;
}
}
new Service()
.onUpdate.subscribe((evt: any) => {
console.log(evt.data);
})
.doSomething()
.onUpdate.publish({ data: 12 });
Clearing
Removing every registered handler and piped observer:
observer.clear();
License
This project is licensed under the MIT License - see the LICENSE.md file for details.