React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript 1.7
class CounterService {
constructor() {
this.counter = 0
this.observers = []
this.tic = this.tic.bind(this)
this.subscribe = this.subscribe.bind(this)
this.notify = this.notify.bind(this)
this.notifyAll = this.notifyAll.bind(this)
setInterval(this.tic, 1000)
}
subscribe(observer) {
this.observers.push(observer)
this.notify(observer)
}
notify(observer) {
observer.next(this.counter)
}
notifyAll() {
this.observers.forEach(this.notify)
}
tic() {
this.counter += 1
this.notifyAll()
console.log(this.counter)
}
}
const ServiceSingleton = new CounterService()
const CounterServiceConnector = (Component) => {
return class ConnectedComponent extends React.Component {
constructor(props){
super(props)
this.state = {
counter: 0
}
}
componentDidMount() {
ServiceSingleton.subscribe({
next: counter => this.setState({ counter })
})
}
render() {
const { counter } = this.state
return <Component counter={counter}/>
}
}
}
const Counter = CounterServiceConnector(({ counter }) => {
return <div>You're looking at this counter since {counter}s</div>
})
const CounterV2 = CounterServiceConnector(({ counter }) => {
return <div>You're looking at this counter 2 since {counter}s</div>
})
const Demo = () => {
return <div><Counter/><CounterV2/></div>
}
ReactDOM.render(
<Demo />,
document.getElementById('container')
);