Skip to content

Instantly share code, notes, and snippets.

@andrew8088
Created June 15, 2015 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrew8088/3a1a67b8ad466bec939f to your computer and use it in GitHub Desktop.
Save andrew8088/3a1a67b8ad466bec939f to your computer and use it in GitHub Desktop.
The Flux store creator that I'm currently using (with Facebook's own flux repo, which includes just a dispatcher). `chirps.js` is an example of it in action.
var constants = require('../constants');
var ChirpStore = module.exports = require('./store').extend({
init: function () {
this.bind(constants.RECEIVE_CHIRPS, this.loadChirps);
this.bind(constants.CREATED_CHIRP, this.loadChirps);
},
loadChirps: function (data) {
data = ({}).toString.call(data).indexOf('Array') > 0 ? data : [data];
data.forEach(ChirpStore.add.bind(ChirpStore));
}
});
var assign = require('object-assign');
var CHANGE_EVENT = 'CHANGE';
exports.extend = function (methods) {
var store = assign({}, require('events').EventEmitter.prototype, {
_id: 0,
_data: {},
add: function (obj) {
if (!obj.id) {
var id = this._id++;
obj.id = id;
} else {
if (obj.id > this._id) this._id = obj.id;
}
this._data[obj.id] = obj;
return obj;
},
all: function () {
return Object.keys(this._data).map(function (id) { return this._data[id]; }.bind(this));
},
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
actions: {},
bind: function (actionType, action) {
this.actions[actionType] = action.bind(this);
}
}, methods);
store.init();
require('../dispatcher').register(function (action) {
store.actions[action.actionType](action.data);
store.emitChange();
});
return store;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment