Created
December 11, 2014 05:20
-
-
Save blakeembrey/7a587bacd9aa784d22dd to your computer and use it in GitHub Desktop.
Example React Store
This file contains 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
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