1.1.1 • Published 8 years ago
update-creator v1.1.1
Update creator
Create an update function to pass messages to child components.
This idea is inspired by TEA (The Elm Architecture).
The library is originally designed to work with React components. But technically, it's applicable to any UI libraries/frameworks
Install
npm install --save update-creatorUsage
Create a child component Child.js
const Child = ({ onClick, onSubmit, onChange }) => {
return (
<div>
<button onClick={onClick}>Cancel</button>
<input onChange={onChange} name="title" />
<button onClick={() => onSubmit({ title: 'foo bar' })}>Submit</button>
</div>
)
}
export default ChildCreate constants for reusable messages Constants.js
export const MSG = {
CLICK: 'ON_CLICK',
SUBMIT: 'ON_SUBMIT',
CHANGE: 'ON_CHANGE'
}Create the parent component
import React from 'react'
import updateCreator from 'update-creator'
import Child from './Child'
import { MSG } from './Constants'
const { CLICK, SUBMIT, CHANGE } = MSG
const parentMessages = [
CLICK,
SUBMIT,
CHANGE
]
class Parent extends React.Component {
update = updateCreator({
[CLICK]: () => {
console.log('on click')
},
[SUBMIT]: (values) => {
console.log('values', values)
},
[CHANGE]: (event) => {
console.log('current value', event.target.value)
}
}, parentMessages)
render() {
return (
<Child
onClick={this.update(CLICK)}
onSubmit={this.update(SUBMIT)}
onChange={this.update(CHANGE)}
/>
)
}
}API Reference
updateCreator(actions, messages = [])
actionsis a required object that contains event handlers, follow this pattern[message]: eventHandlermessagesis an optional array of messages. However, it's recommended to specify it so the library can detect whether theupdatefunction covers all possibilities
License
MIT