Skip to content

Instantly share code, notes, and snippets.

@btpoe
Created April 12, 2017 16:07
Show Gist options
  • Save btpoe/d3ae7bad3900490dda75735ae53a9c29 to your computer and use it in GitHub Desktop.
Save btpoe/d3ae7bad3900490dda75735ae53a9c29 to your computer and use it in GitHub Desktop.
React Service Layer
let listener = null;
export default {
set listener(value) {
listener = value;
listener.state.items = [];
},
get all() {
return listener.state.items;
},
set all(items) {
listener.setState({ items });
},
add(value) {
const items = this.items.slice();
items.push(value);
this.all = items;
},
remove(name) {
this.all = this.items.filter(item => item.name !== name);
},
}
import React, { Component, createElement } from 'react';
import items from './items-service.js';
function handleRemoveItem(name) {
return () => {
items.remove(name);
};
}
export default props =>
createElement(
'div',
null,
createElement(
'button',
{ onClick: handleRemoveItem(props.name) },
'remove item'
)
);
import React, { Component, createElement } from 'react';
import items from './items-service.js';
import LowLevel from './LowLevel.js';
function handleAddItem() {
items.add({ name: Math.random() });
}
export default class TopLevel extends Component {
constructor(props) {
super(props);
this.state = {};
service.listener = this;
}
render() {
return createElement(
'div',
null,
items.all.map(item => createElement(LowLevel, item)),
createElement(
'button',
{ onClick: handleAddItem },
'add item'
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment