README
react-context-event
rapid event emitter and listener as hoc
(https://www.npmjs.com/package/react-context-event)
This lib contains HOC-functions witch provides into WrappedComponent
ability to emit messages to parent components and subscribe for events from child components
WrappedComponent
)
1) withEvent(
- your react class-component or functional-component WrappedComponent
Implements the following functions into the component: on, emit
Event
, Message
, userInfo(optional)
)
emit(Sends a message to itself and all components above the hierarchy subscribed to Event
example:
const EmitterComponent = withEvent({emit}) => (
<button onClick={() => emit("paybutton:click", {amount:500, productId:1})}>Buy product 1</button>
));
Event
, Handler
)
on(subscribe component to ʻEventusing the callback
Handler`
Handler = (Message, Handler_of_parent_context_with_same_Event) => { /* process */ }
example:
const HandlerComponent = withEvent(({on, emit, children}) => {
on("paybutton:click", (data, next) => {
next(data);
alert(data)
});
return (
<fieldset>
Handler
{children}
</fieldset>
)
});
WrappedComponent
, StatefulSubscriptions
)
2) withEventState(Map subscriptions to props of WrappedComponent + all functions of HOC withEvent
- your react class-component or functional-component WrappedComponent
- object with keys like StatefullSubscriptionsEvent
, values like [Handler(){}
, initial_state
]
const StatefullSubscriptions = [
(prevState, message, next, emit) => { // `Handler`
return "data from handled message which passed into the `WrappedComponent` Props by key `Event`"
},
"" // `initial_state`
]
Implements the following props into the component: resetEventState
, ...eventProps
- function which resets eventProps to their resetEventStateinitial_state
- data received from handled messages ...eventProps
example:
const HandlerComponent = withEventState({on, emit, resetEventState, children, ...eventProps}) => {
on("paybutton:click", (data, next) => {
next(data);
alert(data)
});
return (
<fieldset>
{
eventProps['error:nomoney']
? (<p>
Need more gold {eventProps['error:nomoney'].amountText}!
<button onClick={() => resetEventState('error:nomoney')}>ok</button>
</p>)
: null
}
{children}
</fieldset>
)
}, {
"error:nomoney": [
function (prevState, data, next, emit) {
next({...data, handeled:true}); // you can change this message for parent components
// the return value will be passed to props['error:nomoney']
return {...data, amountText: "