Code coverage report for ReactFlux/lib/store.js

Statements: 97.78% (132 / 135)      Branches: 92.06% (58 / 63)      Functions: 97.5% (39 / 40)      Lines: 97.78% (132 / 135)      Ignored: none     

All files » ReactFlux/lib/ » store.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 3861 1 1 1 1   1   1     1 51   51 85       44       1 1 1           1       4     51 2                     1 51     51 51 51 51 51 51 51   51 51 51 39   43 4         1           85 85             1 1               7       1       1       2                 23 23 23                 2 1   1 1 1                   6 1     5   5 1   4               1 1             1 1             1 1             24             4             1                 54 2   54 44 2     42 42     42 4 38 4   34                     16 16               59 1   58 177 1   176   176 176 159 159     17 17   176 2   174 1   173 1   172 172 16 16 1   15       171 171 170                   16 1   15             51                 51   51 4     51                             1                   4 3   4 4                 1 1 2 1 1                     86 74   12 12 12 12             1  
var _assign = require('lodash-node/modern/object/assign');
var _forEach = require('lodash-node/modern/collection/forEach');
var _isArray = require('lodash-node/modern/lang/isArray');
var _cloneDeep = require('lodash-node/compat/lang/cloneDeep');
var MixinFor = require('./mixinFor');
 
var CHANGE_EVENT = 'change';
 
var StoreActionHandler = require('./storeActionHandler');
 
 
function FluxState(initState) {
	var _state = initState;
 
	this.assign = function (newState) {
		_state = _assign(_state, newState);
	},
 
	this.get = function (key) {
		return _state[key] || undefined;
	},
 
	this.getClone = function (key) {
		var v = _state[key] || undefined;
		Eif (v instanceof Object && v !== null) {
			return _cloneDeep(v);
		}
		return v;
	},
 
	this.replaceState = function (newState) {
		_state = newState;
	},
 
	this.getState = function () {
		return _state;
	}
 
	this.getStateClone = function () {
		return _cloneDeep(_state);
	}
 
}
 
/**
 * Flux Store
 * @param {object} dispatcher
 * @param {object} storeMixin
 * @param {array} handlers
 */
var Store = function (dispatcher, storeMixin, handlers) {
	this.state = new FluxState({
		_action_states: {}
	});
	this._events = {};//used by store event emitter
	this._actionHandlers = {};
	this._constantHandlers = {};
	this._dispatcherIndexes = {};
	this._dispatcher = dispatcher;
	this._getInitialStateCalls = [];
	this._storeDidMountCalls = [];
 
	this._storeMixin(storeMixin);
	this._setInitialState();
	if (!!handlers) {
		this._setConstantHandlers(handlers);
	}
	_forEach(this._storeDidMountCalls, function (fn) {
		fn();
	});
};
 
 
Store.prototype = {
 
	/**
	 * @param {object} newState
	 */
	setState: function (newState) {
		this.state.assign(newState);
		this._emit(CHANGE_EVENT);
	},
 
	/**
	 * @param {object} newState
	 */
	replaceState: function (newState) {
		this.state.replaceState(newState);
		this._emit(CHANGE_EVENT);
	},
 
	/**
	 * @param {string} propertyName
	 * @return {mixed}
	 */
	get: function (propertyName) {
		return this.state.get(propertyName);
	},
 
	getClone: function (propertyName) {
		return this.state.getClone(propertyName);
	},
 
	getState: function () {
		return this.state.getState();
	},
 
	getStateClone: function () {
		return this.state.getStateClone();
	},
 
 
	/**
	 * @param {string} constant
	 * @param {object} newState
	 */
	setActionState: function (constant, newState) {
		var actionStates = this.state.get('_action_states');
		actionStates[constant] = _assign(actionStates[constant] || {}, newState);
		this.setState({
			'_action_states': actionStates
		});
	},
 
	/**
	 * @param {string} constant
	 */
	resetActionState: function (constant) {
		if (typeof this._actionHandlers[constant] === 'undefined') {
			throw new Error('Store.resetActionState constant handler for [' + constant + '] is not defined');
		}
		var actionStates = this.state.get('_action_states');
		actionStates[constant] = this._actionHandlers[constant].getInitialState();
		this.setState({
			'_action_states': actionStates
		});
	},
 
	/**
	 * @param {string} constant - constant to get handler state for
	 * @param {string} [key] - a specfic key to get
	 */
	getActionState: function (constant, key) {
		if (typeof this._actionHandlers[constant] === 'undefined') {
			throw new Error('Store.getActionState constant handler for [' + constant + '] is not defined');
		}
 
		var actionState = this.state.get('_action_states');
 
		if (typeof key === "undefined") {
			return actionState[constant];
		}
		return actionState[constant][key] || undefined;
	},
 
 
	/**
	 * @return {object} Store's state
	 */
	toJS: function () {
		console.warn('toJS is deprecated. Please use store.getState instead');
		return this.state.getState();
	},
 
	/**
	 * @return {object} Store's state
	 */
	toObject: function () {
		console.warn('toObject is deprecated. Please use store.getState instead');
		return this.state.getState();
	},
 
	/**
	 *
	 */
	toJSON: function () {
		console.warn('toJSON is deprecated. Please use store.getState instead');
		return this.state.getState();
	},
 
	/**
	 *
	 */
	isStore: function () {
		return true;
	},
 
	/**
	 * @param {function} callback
	 */
	onChange: function (callback) {
		this._on(CHANGE_EVENT, callback);
	},
 
	/**
	 * @param {function} callback
	 */
	offChange: function (callback) {
		this._off(CHANGE_EVENT, callback);
	},
 
 
	/**
	 * set extra properties & methods for this Store
	 * @param {object} storeMixin
	 */
	_storeMixin: function (storeMixin) {
		if (storeMixin && storeMixin.mixins && _isArray(storeMixin.mixins)) {
			_forEach(storeMixin.mixins, this._storeMixin.bind(this));
		}
		_forEach(storeMixin, function (prop, propName) {
			if (propName === 'mixins') {
				return;
			}
 
			Eif (typeof prop === 'function') {
				prop = prop.bind(this);
			}
 
			if (propName === 'getInitialState') {
				this._getInitialStateCalls.push(prop);
			} else if (propName === 'storeDidMount') {
				this._storeDidMountCalls.push(prop);
			} else {
				this[propName] = prop;
			}
		}.bind(this));
	},
 
	/**
	 * @param {string} constant
	 * @param {object} configs
	 * @return {FluxStore} self
	 */
	addActionHandler: function (constant, configs) {
		this._actionHandlers[constant] = new StoreActionHandler(this, constant, configs);
		return this;
	},
 
	/**
	 * Set constant handlers for this Store
	 * @param {array} handlers
	 */
	_setConstantHandlers: function (handlers) {
		if (!_isArray(handlers)) {
			throw new Error('store expects handler definitions to be an array');
		}
		_forEach(handlers, function (options) {
			if (!_isArray(options)) {
				throw new Error('store expects handler definition to be an array');
			}
			var constant, handler, waitFor;
 
			constant = options[0];
			if (options.length === 2) {
				waitFor = null;
				handler = options[1];
			}
			else {
				waitFor = options[1];
				handler = options[2];
			}
			if (typeof constant !== 'string') {
				throw new Error('store expects all handler definitions to contain a constant as the first parameter');
			}
			if (typeof handler !== 'function') {
				throw new Error('store expects all handler definitions to contain a callback');
			}
			if (!!waitFor && !_isArray(waitFor)) {
				throw new Error('store expects waitFor to be an array of stores');
			}
			var waitForIndexes = null;
			if (waitFor) {
				waitForIndexes = waitFor.map(function (store) {
					if (!(store instanceof Store)) {
						throw new Error('store expects waitFor to be an array of stores');
					}
					return store._getHandlerIndex(constant);
				});
			}
 
			this._constantHandlers[constant] = handler.bind(this);
			var dispatcherIndex = this._dispatcher.register(constant, this._constantHandlers[constant], waitForIndexes);
			this._dispatcherIndexes[constant] = dispatcherIndex;
		}.bind(this));
	},
 
	/**
	 * Get dispatcher idx of this constant callback for this store
	 * @param {string} constant
	 * @return {number} Index of constant callback
	 */
	_getHandlerIndex: function (constant) {
		if (typeof this._dispatcherIndexes[constant] === "undefined") {
			throw new Error('Can not get store handler for constant: ' + constant);
		}
		return this._dispatcherIndexes[constant];
	},
 
	/**
	 * Sets intial state of the Store
	 */
	_setInitialState: function () {
		this.setState(this.getInitialState());
	},
 
	/**
	 * Gets initial state of the store
	 *
	 * @return {mixed} Store initial state
	 */
	getInitialState: function () {
		var state = {};
 
		_forEach(this._getInitialStateCalls, function (fn) {
			_assign(state, fn());
		});
 
		return state;
	},
 
	/**
	 * @return {Object} A mixin for React Components
	 */
	mixin: function () {
		console.warn("store.mixin will be deprecated, please use store.mixinFor")
		return MixinFor(this);
	},
 
	/**
	 * @return {Object} A mixin for React Components
	 */
	mixinFor: function () {
		return MixinFor(this);
	},
 
	/**
	 *
	 * @param {String} evt
	 * @param {Function} handler
	 * @return  {Function} handler
	 */
	_on: function (evt, handler) {
		if (typeof this._events[evt] === 'undefined') {
			this._events[evt] = [];
		}
		this._events[evt].push(handler);
		return handler;
	},
 
	/**
	 *
	 * @param {String} evt
	 * @param {Function} handler
	 */
	_off: function (evt, handler) {
		Eif (typeof this._events[evt] !== 'undefined') {
			for (var i = 0, len = this._events[evt].length; i < len; i++) {
				if (this._events[evt][i] === handler) {
					this._events[evt].splice(i, 1);
					break;
				}
			}
		}
	},
 
	/**
	 *
	 * @param {String} evt
	 */
	_emit: function (evt) {
		if (typeof this._events[evt] === 'undefined') {
			return;
		}
		var args = Array.prototype.slice.call(arguments, 1);
		_forEach(this._events[evt], function (listener) {
			Eif ('function' === typeof listener) {
				listener.apply(null, args);
			}
		});
	},
 
};
 
module.exports = Store;