https://github.com/ziflex/observable-mixin
Makes your types observable
https://github.com/ziflex/observable-mixin
Last synced: 3 months ago
JSON representation
Makes your types observable
- Host: GitHub
- URL: https://github.com/ziflex/observable-mixin
- Owner: ziflex
- License: mit
- Created: 2017-01-10T18:19:41.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2017-01-10T18:58:49.000Z (over 8 years ago)
- Last Synced: 2025-02-24T06:19:20.790Z (3 months ago)
- Language: JavaScript
- Size: 28.3 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# observable-mixin
> Just observe
Mixin that makes your types observable without exposing emitter.
[](https://www.npmjs.com/package/observable-mixin)
[](http://travis-ci.org/ziflex/observable-mixin)
[](https://coveralls.io/github/ziflex/observable-mixin)````sh
npm install --save observable-mixin
````## Usage
``observable-mixin`` brings 1 method:
- ``subscribe(eventName: String, handler: Function, [once: Boolean]): Function`` returns a function that unsubscribes a given listenerThe mixin comes as a factory function i.e. in order to get mixin it needs to invoke exported function.
It is done intentionally in order to be able to pass any kind of implementation of EventEmitter.````javascript
import Symbol from 'es6-symbol';
import composeClass from 'compose-class';
import ObservableMixin from 'observable-mixin';
import { EventEmitter } from 'events';const FIELDS = {
emitter: Symbol('emitter'),
name: Symbol('name')
};const Person = composeClass({
mixins: [
ObservableMixin(FIELDS.emitter)
],constructor(name) {
this[FIELDS.emitter] = new EventEmitter();
this[FIELDS.name] = name;
},name(value) {
if (value) {
this[FIELDS.name] = value;
this[FIELDS.emitter].emit('change', 'name', value);
}return this[FIELDS.name];
}
});````
````javascript
import Person from './person';const person = new Person('Mike Wazowski');
const unsubscribe = person.subscribe('change', (field, value) => {
console.log('Person\'s', field, 'was changed to', value);
});person.name('James P. Sullivan'); // Person's name was changed to 'James P. Sullivan'
unsubscribe();
person.name('Randall Boggs'); // Nothing
````
Mixin supports ``once`` subscription:
````javascript
import Person from './person';const person = new Person('Mike Wazowski');
person.subscribe('change', (field, value) => {
console.log('Person\'s', field, 'was changed to', value);
}, true);person.name('James P. Sullivan'); // Person's name was changed to 'James P. Sullivan'
person.name('Randall Boggs'); // Nothing
````