ben tedder : code issues

Creating a base store for Flux and React in Node.js

When writing applications using Flux, I've found I do a lot of repeating of boilerplate code. So I've abstracted away at least 20 or so lines from every Store I create. Seems they all do some similar things. Check this out:

var assign = require('object-assign');
var EventEmitter = require('events').EventEmitter;
var CHANGE_EVENT = 'change';

var BaseStore = assign({}, EventEmitter.prototype, {

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
});

module.exports = BaseStore;

Now every time I create a new store, I simply assign this base store to it like so:

var assign = require('object-assign');
var BaseStore = require('./BaseStore');

var MyNewStore = assign({}, BaseStore, {

  customFunction: function() {
    
  }

});

...attach dispatcher down here

Actually, where I have customFunction is where I usually place the function that the React component calls to fetch its state. So a more accurate version of that store goes something like:

var assign = require('object-assign');
var BaseStore = require('./BaseStore');

va _storeState = {};

var MyNewStore = assign({}, BaseStore, {

  returnState: function() {
    return _storeState;
  }

});

...attach dispatcher down here