Last active
August 29, 2015 14:19
-
-
Save pgoldrbx/c592b14da180c927591e to your computer and use it in GitHub Desktop.
Flux demo
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
'use strict'; | |
var dispatcher = require('flux').dispatcher; | |
exports.load = function () { | |
dispatcher.dispatch('LOAD', { | |
foo: 'bar' | |
}); | |
}; |
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
'use strict'; | |
var React = require('react'); | |
var MyStore = require('../stores').MyStore; | |
var load = require('actions').load; | |
var MyComp = React.createClass({ | |
getInitialState: function () { | |
return MyStore.getState(); | |
}, | |
handleStoreChange: function () { | |
var storeState = MyStore.getState(); | |
this.setState({ | |
foo: storeState.foo | |
}); | |
}, | |
componentDidMount: function () { | |
MyStore.onChange(this.handleStoreChange); | |
}, | |
componentWillUnmount: function () { | |
MyStore.removeListener(this.handleStoreChange); | |
}, | |
fetchData: function () { | |
load(); | |
}, | |
render: function () { | |
return ( | |
<div> | |
<div>{this.state.foo || ''}</div> | |
<a onClick={this.fetchData}>Fetch</a> | |
</div> | |
); | |
} | |
}); | |
module.exports = MyComp; |
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
'use strict'; | |
var _ = require('lodash'); | |
var EventEmitter = require('events').EventEmitter; | |
var dispatcher = require('flux').dispatcher; | |
var CHANGE_EVENT = 'CHANGE'; | |
// this is ugly | |
// util.createStore | |
exports.MyStore = _.merge({}, EventEmitter.prototype, { | |
state: {}, | |
emitChange: function() { | |
this.emit(CHANGE_EVENT); | |
}, | |
onChange: function(callback) { | |
this.on(CHANGE_EVENT, callback); | |
}, | |
removeListener: function (callback) { | |
this.removeListener(CHANGE_EVENT, callback); | |
}, | |
handleAction: dispatcher.register(function (action, payload) { | |
switch (action) { | |
case 'LOAD': | |
this.state = payload; | |
break; | |
default: | |
return; | |
} | |
this.emitChange(); | |
}) | |
getState: function () { | |
return this.state; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment