Created
January 22, 2016 22:30
-
-
Save jonahwilliams/a9ead9138564d64ea3d3 to your computer and use it in GitHub Desktop.
Flux pattern w/ Webworker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"/> | |
<title>Webworker Redux</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script> | |
<script src="/index.js"></script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global React, ReactDOM */ | |
'use strict'; | |
var worker = new Worker('/worker.js'); | |
var PostMessage = function(type, payload) { | |
return function() { | |
worker.postMessage({type, payload}); | |
}; | |
}; | |
// API | |
var INCREASE = 'INCREASE'; | |
var DECREASE = 'DECREASE'; | |
// View | |
var App = React.createClass({ | |
getInitialState: function() { | |
return { counter: 0 }; | |
}, | |
componentWillMount: function() { | |
worker.onmessage = function(e) { | |
this.setState(e.data); | |
}.bind(this); | |
}, | |
render: function() { | |
return ( | |
React.createElement( | |
'div', | |
null, | |
React.createElement( | |
'div', | |
null, | |
this.state.counter | |
), | |
React.createElement( | |
'button', | |
{ onClick: PostMessage(INCREASE)}, | |
'+' | |
), | |
React.createElement( | |
'button', | |
{ onClick: PostMessage(DECREASE)}, | |
'-' | |
))); | |
} | |
}); | |
ReactDOM.render(React.createElement(App), document.getElementById('app')); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var INCREASE = 'INCREASE'; | |
var DECREASE = 'DECREASE'; | |
var state = { counter : 0 }; | |
function Reducer(action) { | |
switch(action.type) { | |
case INCREASE: | |
return { counter: state.counter + 1 }; | |
case DECREASE: | |
return { counter: state.counter - 1}; | |
default: | |
return state; | |
} | |
} | |
postMessage(state); | |
self.onmessage = function(e) { | |
state = Reducer(e.data); | |
postMessage(state); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment