All Projects → lilactown → observe-component

lilactown / observe-component

Licence: MIT license
A library for accessing React component events as reactive observables

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
shell
77523 projects

Projects that are alternatives of or similar to observe-component

observable-playground
Know your Observables before deploying to production
Stars: ✭ 96 (+166.67%)
Mutual labels:  rxjs, observable, kefir, reactive-programming
ng-observe
Angular reactivity streamlined...
Stars: ✭ 65 (+80.56%)
Mutual labels:  rxjs, observable, reactive-programming
Redux Most
Most.js based middleware for Redux. Handle async actions with monadic streams & reactive programming.
Stars: ✭ 137 (+280.56%)
Mutual labels:  rxjs, observable, reactive-programming
Evolui
A tiny reactive user interface library, built on top of RxJs.
Stars: ✭ 43 (+19.44%)
Mutual labels:  rxjs, observable, reactive-programming
Recycle
Convert functional/reactive object description using RxJS into React component
Stars: ✭ 374 (+938.89%)
Mutual labels:  rxjs, observable, reactive-programming
rxjs-proxify
Turns a Stream of Objects into an Object of Streams
Stars: ✭ 34 (-5.56%)
Mutual labels:  rxjs, observable, reactive-programming
Od Virtualscroll
🚀 Observable-based virtual scroll implementation in Angular
Stars: ✭ 133 (+269.44%)
Mutual labels:  rxjs, observable, reactive-programming
Rx Sandbox
Marble diagram DSL based test suite for RxJS 6
Stars: ✭ 151 (+319.44%)
Mutual labels:  rxjs, observable
Awesome Reactive Programming
A repository for sharing all the resources available on Reactive Programming and Reactive Systems
Stars: ✭ 163 (+352.78%)
Mutual labels:  rxjs, reactive-programming
observable-profiler
Tracks new & disposed Observable subscriptions
Stars: ✭ 41 (+13.89%)
Mutual labels:  rxjs, observable
ObservableComputations
Cross-platform .NET library for computations whose arguments and results are objects that implement INotifyPropertyChanged and INotifyCollectionChanged (ObservableCollection) interfaces.
Stars: ✭ 94 (+161.11%)
Mutual labels:  observable, reactive-programming
Pharmacist
Builds observables from events.
Stars: ✭ 221 (+513.89%)
Mutual labels:  observable, reactive-programming
reactive-angular-workshop
This is the source code for the world's greatest Reactive Angular Workshop.
Stars: ✭ 30 (-16.67%)
Mutual labels:  rxjs, reactive-programming
Jupyterlab Data Explorer
First class datasets in JupyterLab
Stars: ✭ 146 (+305.56%)
Mutual labels:  rxjs, observable
Awesome Rxjs
Awesome list of RxJS 5
Stars: ✭ 141 (+291.67%)
Mutual labels:  rxjs, observable
vuse-rx
Vue 3 + rxjs = ❤
Stars: ✭ 52 (+44.44%)
Mutual labels:  rxjs, reactive-programming
Marble
Marble.js - functional reactive Node.js framework for building server-side applications, based on TypeScript and RxJS.
Stars: ✭ 1,947 (+5308.33%)
Mutual labels:  rxjs, observable
mst-effect
💫 Designed to be used with MobX-State-Tree to create asynchronous actions using RxJS.
Stars: ✭ 19 (-47.22%)
Mutual labels:  rxjs, observable
realar
5 kB Advanced state manager for React
Stars: ✭ 41 (+13.89%)
Mutual labels:  observable, reactive-programming
spellbook
Spellbook is a bookmark extension for Chrome and Firefox
Stars: ✭ 19 (-47.22%)
Mutual labels:  rxjs, kefir

observe-component

import React from 'react';
import { render } from 'react-dom';
import { observeComponent, fromComponent } from 'observe-component/kefir';

const ObservableButton = observeComponent('onClick')('button');

function MyButton(props) {
	return (<ObservableButton>Hello</ObservableButton>);
}

render(<MyButton />, Document.getElementById('my-app'));

const clickObservable =
	fromComponent(ObservableButton);

clickObservable
	.onValue(() => {
		console.log('world!');
	});

Installation

npm install --save observe-component

You will also need to install your choice of Kefir, RxJS (v4), or RxJS (v5+), and React if they're not already a part of your project.

API

observeComponent(...events)(Component)

observeComponent(...events) returns a function that, when applied to a React component, returns a higher-order ObservableComponent with an attached observable of the specified events. Supports all events supported by React's event system.

Example:

const ObservableDiv = observeComponent('onMouseDown', 'onMouseUp')('div');

fromComponent(ObservableComponent, ...events)

Returns the observable attached to the ObservableComponent. Optional string event parameters can be supplied to return a observable only containing those events.

fromComponent observables emit a ComponentEvent object.

Example:

const ObservableDiv = observeComponent('onMouseDown', 'onMouseUp')('div');

// with the Kefir library, we can use the `log()` operator,
// which will log all 'onMouseDown' and 'onMouseUp' events
fromComponent(ObservableDiv).log()

// will only log 'onMouseUp' events
fromComponent(ObservableDiv, 'onMouseUp').log();

ComponentEvent

The ComponentEvent object contains three properties:

  • type : a string which identifies the event that has occurred, e.g.: 'onClick', 'onScroll'
  • value : typically the React library SyntheticEvent (see: Event System)
  • props : the props of the observed component at event trigger

But why?

Because Functional Reactive Programming is pretty cool, and so is React. However, React's API is not very FRP-friendly; the necessity to wire up events by hand using buses (or subjects, in RxJS-speak) easily leads us to the Bus of Doom, and in general is finnicky and boilerplate-y to connect an observer to React.

There are also plenty of libraries for connecting observables to React, but very few (none that I've found) that transition React events to observables, enabling a fully functional reactive architecture.

Dependencies

At the moment, observe-component allows a consumer to use either Kefir, RxJS v4 or RxJS v5 for observables. Support for more FRP libraries might become available if it is highly desired. To use your choice of library, you can import like so:

/* ES6 module syntax */
// kefir.js
import { observeComponent, fromComponent } from 'observe-component/kefir';

// ...
const Button = observeComponent('onClick')('button');
const clickObservable =
	fromComponent(Button, 'onClick')

clickObservable
	.onValue((e) => console.log(e));

// => ComponentEvent { type: 'onClick', value: SyntheticEvent, props: {} }
// RxJS v4
import { observeComponent, fromComponent } from 'observe-component/rx';

// ...
const Button = observeComponent('onClick')('button');
const clickObservable =
	fromComponent(Button, 'onClick');

clickObservable
	.subscribe((e) => console.log(e));

// => ComponentEvent { type: 'onClick', value: SyntheticEvent, props: {} }
// RxJS v5+
import { observeComponent, fromComponent } from 'observe-component/rxjs';

// ...
const Button = observeComponent('onClick')('button');
const clickObservable =
	fromComponent(Button, 'onClick');

clickObservable
	.subscribe((e) => console.log(e));

// => ComponentEvent { type: 'onClick', value: SyntheticEvent, props: {} }

Examples

For these examples, I will use the Kefir library. RxJS is quite similar.

Components as stateless functions

import React, { Component } from 'react';
import { render } from 'react-dom';
import { observeComponent, fromComponent } from 'observe-component/kefir';

const ObservableInput = observeComponent('onChange')('input');

function MyApp(props) {
	return (
		<div>
			<div>Hello {this.props.name}!</div>
			<ObservableInput type="text" value={props.name} />
		</div>
	);
}

const nameObservable =
	fromComponent(ObservableInput)
	/* The observables values contain three properties:
		'type': The type of the event that was triggered, e.g. 'onChange'
		'value': The React library `SyntheticEvent`
		'props': the current props on the component
	*/
	.map(({ value }) => value.target.value);

nameObservable
	.onValue((name) => 
		render(<MyApp name={name} />, document.getElementById('my-app'))
	);

Dynamic lists

const ObservableItem = observeComponent('onClick')('li');

function MyList(props) {
	return (
        <div>
            <span>Selected: { currentName }</span>
            <ul style={styles.ul}>
                {['John', 'Will', 'Marie'].map((name) => 
                    <ObservableItem key={name}>
                        { name }
                    </ObservableItem>
                )}
            </ul>
        </div>
	);
}

fromComponent(ObservableLi)
    .map((ev) => ev.props.children)
    .startWith('John')
    .subscribe((name) => {
        render(<App currentName={name} />, document.getElementById('app'));
    });

Example here

You can observe events from any kind of component

...as long as you handle events appropriately. The library simply passes special handlers to React's event system (on<Event>) to abstract them into observables.

class MyWidget extends React.Component {
	render() {
		return (
			<div>
				<button onClick={this.props.onClick}>Click me!</button>
				<input onChange={this.props.onChange} defaultValue="Change me!" />
			</div>
		);
	}
}

const ObservableWidget = observeComponent('onClick', 'onChange')(MyWidget);
const widgetObservable = 
	fromComponent(ObservableWidget);

widgetObservable
	.onValue(({type, value}) => {
		if (type === 'onClick') {
			console.log('clicked');
		}
		else if (type === 'onChange') {
			console.log('changed: '+value.target.value);
		}
	});

However, you are strongly encouraged to create observables out of basic components and merge them, rather than manually pass the event handlers yourself.

Also, if we can get away with it, we'd always like to use stateless functions as components. :)

import {merge} from 'kefir';

// Create Observable button and Observable inputs
const ObservableButton = observeComponent('onClick')('button');
const ObservableInput = observeComponent('onChange')('input');

// Component is simply a function from props to view
function MyWidget(props) {
	return (
		<div>
			<ObservableButton>Click me!</ObservableButton>
			<ObservableInput defaultValue="Change me!" />
		</div>
	);
}

// We construct our application from the two observables
const widgetObservable = 
	merge([
		fromComponent(ObservableButton),
		fromComponent(ObservableInput),
	]);

widgetObservable
	.onValue(({type, value}) => {
		if (type === 'onClick') {
			console.log('clicked');
		}
		else if (type === 'onChange') {
			console.log('changed: '+value.target.value);
		}
	});

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].