Created
January 14, 2015 13:36
-
-
Save franleplant/4b948e0c205936f7d733 to your computer and use it in GitHub Desktop.
Composability vs "inheritance" in Flux's Stores
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
/* | |
The intention behind this example is to demonstrate how to **compose** | |
instead of **inherit**, this simplifies the code by using EventEmmitter | |
as a service instead of using the pattern know as Prototypal inheritance | |
which is know to have several draw backs, since it **does not work | |
like clasical inheritance** | |
Example Extracted from https://scotch.io/tutorials/getting-to-know-flux-the-react-js-architecture | |
*/ | |
var AppDispatcher = require('../dispatcher/AppDispatcher'); | |
var ShoeConstants = require('../constants/ShoeConstants'); | |
var EventEmitter = require('events').EventEmitter; | |
// Internal object of shoes | |
var _shoes = {}; | |
// Method to load shoes from action data | |
function loadShoes(data) { | |
_shoes = data.shoes; | |
} | |
//Internal event emitter "service" | |
var emitter = new EventEmitter(); | |
// Use Node's Event Emitter in the ShoeStore | |
var ShoeStore = { | |
// Returns all shoes | |
getShoes: function() { | |
return _shoes; | |
}, | |
emitChange: function() { | |
emitter.emit('change'); | |
}, | |
addChangeListener: function(callback) { | |
emitter.on('change', callback); | |
}, | |
removeChangeListener: function(callback) { | |
emitter.removeListener('change', callback); | |
} | |
}); | |
// Register dispatcher callback | |
AppDispatcher.register(function(payload) { | |
var action = payload.action; | |
var text; | |
// Define what to do for certain actions | |
switch(action.actionType) { | |
case ShoeConstants.LOAD_SHOES: | |
// Call internal method based upon dispatched action | |
loadShoes(action.data); | |
break; | |
default: | |
return true; | |
} | |
// If action was acted upon, emit change event | |
ShoeStore.emitChange(); | |
return true; | |
}); | |
module.exports = ShoeStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Other things that we could do to reduce the Store's boilerplate is to use some pattern to avoid rewriting emitChange, addChangeListener and removeChangeListener every time we write a store.