Skip to content

Instantly share code, notes, and snippets.

@blakeembrey
Created December 11, 2014 05:20
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 blakeembrey/7a587bacd9aa784d22dd to your computer and use it in GitHub Desktop.
Save blakeembrey/7a587bacd9aa784d22dd to your computer and use it in GitHub Desktop.
Example React Store
var util = require('util');
var extend = require('extend');
var EventEmitter = require('events').EventEmitter;
var invariant = require('react/lib/invariant');
var CHANGE_EVENT = 'change';
var RESERVED_MESSAGE = '"%s" is a reserved name and not allowed as a method';
function Store (methods) {
var self = this;
invariant(!methods.Mixin, RESERVED_MESSAGE, 'Mixin');
invariant(!methods.dispatcherToken, RESERVED_MESSAGE, 'dispatcherToken');
extend(this, methods);
/**
* Base functionality for every Store constructor. Mixed into the `Store`
* prototype and exposed statically for easy access.
*/
this.Mixin = {
componentWillMount: function () {
self.addChangeListener(this.onChange);
},
componentWillUnmount: function () {
self.removeChangeListener(this.onChange);
}
};
}
util.inherits(Store, EventEmitter);
Store.prototype.emitChange = function () {
this.emit(CHANGE_EVENT);
};
Store.prototype.addChangeListener = function (cb) {
this.on(CHANGE_EVENT, cb);
};
Store.prototype.removeChangeListener = function (cb) {
this.removeListener(CHANGE_EVENT, cb);
};
module.exports = Store;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment