Flux like Pattern in React
HTML
<script src="https://fb.me/JSXTransformer-0.13.0.js"></script>
<script src="https://fb.me/react-with-addons-0.13.0.js"></script>
<script src="http://facebook.github.io/react/js/jsfiddle-integration.js"></script>www
<div id="header">
</div>
<br style="clear:both;margin:10px"/>
<hr/>
<div>
<h4>Menu List</h4>
<div id="content"></div>
</div>
<hr/>
<div id="pager"></div>
CSS
#header {
width: 80%;
}
#header .menu{
padding: 5px;
border: 1px solid silver;
border-radius: 3px;
width: 150px;
float: left;
}
.menu.active{
background-color: seagreen;
color: white;
}
#content{
height: 80px;
}
JavaScript 1.7
//Application State
var MENU = {
Pasta: 0,
Salada: 1
}
//Payload
var Payload = (function () {
function Payload(invokedActionType) {
this.actionType = invokedActionType;
}
console.log('Payload');
return Payload;
})();
//Action
var Action = {
switchMenu: function(menu){
//the role to make the payload is assigned to Action
//http://facebook.github.io/flux/docs/todo-list.html#creating-semantic-actions
Dispatcher.handleViewAction(new Payload(menu));
}
}
//Dispatcher
var Dispatcher = {
callbacks: [],
handleViewAction: function(payload){
this.dispatch(payload);
},
register: function(callback){
this.callbacks.push(callback);
},
dispatch: function(payload){
this.callbacks.forEach(function(cb){
cb(payload);
});
}
}
//Store
var MenuStore = {
menu: MENU.Pasta,
listeners: [],
getMenu: function(){
return this.menu;
},
setMenu: function(menu){
if(this.menu != menu){
this.menu = menu;
//emit the change
this.listeners.forEach(function(cb){
cb();
});
}
},
receive: function(payload){
this.setMenu(payload.actionType);
},
addListener: function(callback){
this.listeners.push(callback);
}
};
//Context expresses the current application states to render the views.
getContext = function(){
return {
menu: MenuStore.getMenu()
}
}
//View(Header)
var Header = React.createClass({
handleClick: function(event) {
var selected = event.target.getAttribute("data-value");
Action.switchMenu(selected);
},
render: function() {
var self = this;
var selected = this.props.context.menu;
var menus = Object.keys(MENU).map(function(m){
return {name:m, value:MENU[m], className: (MENU[m] == selected ? "menu active" : "menu")}
});
var...