(function (DeLorean) {
'use strict';(function (DeLorean) {
'use strict';There are two main concepts in Flux structure: Dispatchers and Stores. Action Creators are simply helpers but doesn’t require any framework level abstraction.
var Dispatcher, Store;Helper functions are private functions to be used in codebase. It’s better using two underscore at the beginning of the function.
/* `__hasOwn` function is a shortcut for `Object#hasOwnProperty` */
function __hasOwn(object, prop) {
return Object.prototype.hasOwnProperty.call(object, prop);
}Use __generateActionName function to generate action names.
E.g. If you create an action with name hello it will be
action:hello for the Flux.
function __generateActionName(name) {
return 'action:' + name;
}
/* It's used by the schemes to save the original version (not calculated)
of the data. */
function __generateOriginalName(name) {
return 'original:' + name;
}__findDispatcher is a private function for React components.
function __findDispatcher(view) {Provide a useful error message if no dispatcher is found
if (DeLorean.dispatcher == null) {
throw 'No dispatcher found. The DeLoreanJS mixin requires a "dispatcher" has been created using Flux.createDispatcher.';
}
return DeLorean.dispatcher;
}__clone creates a deep copy of an object.
function __clone(obj) {
if (obj === null || typeof obj !== 'object') { return obj; }
var copy = obj.constructor();
for (var attr in obj) {
if (__hasOwn(obj, attr)) {
copy[attr] = __clone(obj[attr]);
}
}
return copy;
}__extend adds props to obj
function __extend(obj, props) {
props = __clone(props);
for (var prop in props) {
if (props.hasOwnProperty(prop)) {
obj[prop] = props[prop];
}
}
return obj;
}The dispatcher is the central hub that manages all data flow in a Flux application. It is essentially a registry of callbacks into the stores. Each store registers itself and provides a callback. When the dispatcher responds to an action, all stores in the application are sent the data payload provided by the action via the callbacks in the registry.
Dispatcher = (function () {Rollback listener adds a rollback event listener to the bunch of
stores.
function __rollbackListener(stores) {
function __listener() {
for (var i in stores) {
stores[i].listener.emit('__rollback');
}
}
/* If any of them fires `rollback` event, all of the stores
will be emitted to be rolled back with `__rollback` event. */
for (var j in stores) {
stores[j].listener.on('rollback', __listener);
}
} function Dispatcher(stores) {
var self = this;DeLorean.EventEmitter is require('events').EventEmitter by default.
you can change it using DeLorean.Flux.define('EventEmitter', AnotherEventEmitter)
DeLorean.EventEmitter.defaultMaxListeners = 100;
this.listener = new DeLorean.EventEmitter();
this.stores = stores;
/* Stores should be listened for rollback events. */
__rollbackListener(Object.keys(stores).map(function (key) {
return stores[key];
}));
}dispatch method dispatch the event with data (or payload)
Dispatcher.prototype.dispatch = function () {
var self = this, stores, deferred, args;
args = Array.prototype.slice.call(arguments);
this.listener.emit.apply(this.listener, ['dispatch'].concat(args));
/* Stores are key-value pairs. Collect store instances into an array. */
stores = (function () {
var stores = [], store;
for (var storeName in self.stores) {
store = self.stores[storeName];
/* Store value must be an _instance of Store_. */
if (!store instanceof Store) {
throw 'Given store is not a store instance';
}
stores.push(store);
}
return stores;
}());Store instances should wait for finish. So you can know if all the stores are dispatched properly.
deferred = this.waitFor(stores, args[0]);
/* Payload should send to all related stores. */
for (var storeName in self.stores) {
self.stores[storeName].dispatchAction.apply(self.stores[storeName], args);
}dispatch returns deferred object you can just use promise
for dispatching: dispatch(..).then(..).
return deferred;
};waitFor is actually a semi-private method. Because it’s kind of internal
and you don’t need to call it from outside most of the times. It takes
array of store instances ([Store, Store, Store, ...]). It will create
a promise and return it. Whenever store changes, it resolves the promise.
Dispatcher.prototype.waitFor = function (stores, actionName) {
var self = this, promises;
promises = (function () {
var __promises = [], promise;
/* `__promiseGenerator` generates a simple promise that resolves itself when
related store is changed. */
function __promiseGenerator(store) {DeLorean.Promise is require('es6-promise').Promise by default.
you can change it using DeLorean.Flux.define('Promise', AnotherPromise)
return new DeLorean.Promise(function (resolve, reject) {
store.listener.once('change', resolve);
});
}
for (var i in stores) {Only generate promises for stores that ae listening for this action
if (stores[i].actions && stores[i].actions[actionName] != null) {
promise = __promiseGenerator(stores[i]);
__promises.push(promise);
}
}
return __promises;
}());When all the promises are resolved, dispatcher emits change:all event.
return DeLorean.Promise.all(promises).then(function () {
self.listener.emit('change:all');
});
};registerAction method adds a method to the prototype. So you can just use
dispatcherInstance.actionName().
Dispatcher.prototype.registerAction = function (action, callback) {
/* The callback must be a function. */
if (typeof callback === 'function') {
this[action] = callback.bind(this.stores);
} else {
throw 'Action callback should be a function.';
}
};register method adds an global action callback to the dispatcher.
Dispatcher.prototype.register = function (callback) {
/* The callback must be a function. */
if (typeof callback === 'function') {
this.listener.on('dispatch', callback);
} else {
throw 'Global callback should be a function.';
}
};getStore returns the store from stores hash.
You can also use dispatcherInstance.stores[storeName] but
it checks if the store really exists.
Dispatcher.prototype.getStore = function (storeName) {
if (!this.stores[storeName]) {
throw 'Store ' + storeName + ' does not exist.';
}
return this.stores[storeName].getState();
};
Dispatcher.prototype.on = function () {
return this.listener.on.apply(this.listener, arguments);
};
Dispatcher.prototype.off = function () {
return this.listener.removeListener.apply(this.listener, arguments);
};
Dispatcher.prototype.emit = function () {
return this.listener.emit.apply(this.listener, arguments);
};
return Dispatcher;
}());Stores contain the application state and logic. Their role is somewhat similar to a model in a traditional MVC, but they manage the state of many objects. Unlike MVC models, they are not instances of one object, nor are they the same as Backbone’s collections. More than simply managing a collection of ORM-style objects, stores manage the application state for a particular domain within the application.
Store = (function () { function Store(args) {
if (!this.state) {
this.state = {};
}DeLorean.EventEmitter is require('events').EventEmitter by default.
you can change it using DeLorean.Flux.define('EventEmitter', AnotherEventEmitter)
this.listener = new DeLorean.EventEmitter();
this.bindActions();
this.buildScheme();
this.initialize.apply(this, arguments);
}
Store.prototype.initialize = function () {
};
Store.prototype.get = function (arg) {
return this.state[arg];
};set method updates the data defined at the scheme of the store.
Store.prototype.set = function (arg1, value) {
var changedProps = [];
if (typeof arg1 === 'object') {
for (var keyName in arg1) {
changedProps.push(keyName);
this.setValue(keyName, arg1[keyName]);
}
} else {
changedProps.push(arg1);
this.setValue(arg1, value);
}
this.recalculate(changedProps);
return this.state[arg1];
};set method updates the data defined at the scheme of the store.
Store.prototype.setValue = function (key, value) {
var scheme = this.scheme, definition;
if (scheme && this.scheme[key]) {
definition = scheme[key];This will allow you to directly set falsy values before falling back to the definition default
this.state[key] = (typeof value !== 'undefined') ? value : definition.default;
if (typeof definition.calculate === 'function') {
this.state[__generateOriginalName(key)] = value;
this.state[key] = definition.calculate.call(this, value);
}
} else {Scheme must include the key you wanted to set.
if (console != null) {
console.warn('Scheme must include the key, ' + key + ', you are trying to set. ' + key + ' will NOT be set on the store.');
}
}
return this.state[key];
};Removes the scheme format and standardizes all the shortcuts.
If you run formatScheme({name: 'joe'}) it will return you
{name: {default: 'joe'}}. Also if you run formatScheme({fullname: function () {}})
it will return {fullname: {calculate: function () {}}}.
Store.prototype.formatScheme = function (scheme) {
var formattedScheme = {}, definition, defaultValue, calculatedValue;
for (var keyName in scheme) {
definition = scheme[keyName];
defaultValue = null;
calculatedValue = null;
formattedScheme[keyName] = {default: null};
/* {key: 'value'} will be {key: {default: 'value'}} */
defaultValue = (definition && typeof definition === 'object') ?
definition.default : definition;
formattedScheme[keyName].default = defaultValue;
/* {key: function () {}} will be {key: {calculate: function () {}}} */
if (definition && typeof definition.calculate === 'function') {
calculatedValue = definition.calculate;
/* Put a dependency array on formattedSchemes with calculate defined */
if (definition.deps) {
formattedScheme[keyName].deps = definition.deps;
} else {
formattedScheme[keyName].deps = [];
}
} else if (typeof definition === 'function') {
calculatedValue = definition;
}
if (calculatedValue) {
formattedScheme[keyName].calculate = calculatedValue;
}
}
return formattedScheme;
};
/* Applying `scheme` to the store if exists. */
Store.prototype.buildScheme = function () {
var scheme, calculatedData, keyName, definition, dependencyMap, dependents, dep, changedProps = [];
if (typeof this.scheme === 'object') {
/* Scheme must be formatted to standardize the keys. */
scheme = this.scheme = this.formatScheme(this.scheme);
dependencyMap = this.__dependencyMap = {};
/* Set the defaults first */
for (keyName in scheme) {
definition = scheme[keyName];
this.state[keyName] = __clone(definition.default);
}
/* Set the calculations */
for (keyName in scheme) {
definition = scheme[keyName];
if (definition.calculate) {Create a dependency map - {keyName: [arrayOfKeysThatDependOnIt]}
dependents = definition.deps || [];
for (var i = 0; i < dependents.length; i++) {
dep = dependents[i];
if (dependencyMap[dep] == null) {
dependencyMap[dep] = [];
}
dependencyMap[dep].push(keyName);
}
this.state[__generateOriginalName(keyName)] = definition.default;
this.state[keyName] = definition.calculate.call(this, definition.default);
changedProps.push(keyName);
}
}Recalculate any properties dependent on those that were just set
this.recalculate(changedProps);
}
};
Store.prototype.recalculate = function (changedProps) {
var scheme = this.scheme, dependencyMap = this.__dependencyMap, didRun = [], definition, keyName, dependents, dep;Only iterate over the properties that just changed
for (var i = 0; i < changedProps.length; i++) {
dependents = dependencyMap[changedProps[i]];If there are no properties dependent on this property, do nothing
if (dependents == null) {
continue;
}Iterate over the dependendent properties
for (var d = 0; d < dependents.length; d++) {
dep = dependents[d];Do nothing if this value has already been recalculated on this change batch
if (didRun.indexOf(dep) !== -1) {
continue;
}Calculate this value
definition = scheme[dep];
this.state[dep] = definition.calculate.call(this,
this.state[__generateOriginalName(dep)] || definition.default);Make sure this does not get calculated again in this change batch
didRun.push(dep);
}
}Update Any deps on the deps
if (didRun.length > 0) {
this.recalculate(didRun);
}
this.listener.emit('change');
};
Store.prototype.getState = function () {
return this.state;
};
Store.prototype.clearState = function () {
this.state = {};
return this;
};
Store.prototype.resetState = function () {
this.buildScheme();
this.listener.emit('change');
return this;
};Stores must have a actions hash of actionName: methodName
methodName is the this.store‘s prototype method..
Store.prototype.bindActions = function () {
var callback;
this.emitChange = this.listener.emit.bind(this.listener, 'change');
this.emitRollback = this.listener.emit.bind(this.listener, 'rollback');
this.rollback = this.listener.on.bind(this.listener, '__rollback');
this.emit = this.listener.emit.bind(this.listener);
for (var actionName in this.actions) {
if (__hasOwn(this.actions, actionName)) {
callback = this.actions[actionName];
if (typeof this[callback] !== 'function') {
throw 'Callback \'' + callback + '\' defined for action \'' + actionName + '\' should be a method defined on the store!';
}
/* And `actionName` should be a name generated by `__generateActionName` */
this.listener.on(__generateActionName(actionName), this[callback].bind(this));
}
}
};dispatchAction called from a dispatcher. You can also call anywhere but
you probably won’t need to do. It simply emits an event with a payload.
Store.prototype.dispatchAction = function (actionName, data) {
this.listener.emit(__generateActionName(actionName), data);
};listenChanges is a shortcut for Object.observe usage. You can just use
Object.observe(object, function () { ... }) but everytime you use it you
repeat yourself. DeLorean has a shortcut doing this properly.
Store.prototype.listenChanges = function (object) {
var self = this, observer;
if (!Object.observe) {
console.error('Store#listenChanges method uses Object.observe, you should fire changes manually.');
return;
}
observer = Array.isArray(object) ? Array.observe : Object.observe;
observer(object, function (changes) {
self.listener.emit('change', changes);
});
};onChange simply listens changes and calls a callback. Shortcut for
a on('change') command.
Store.prototype.onChange = function (callback) {
this.listener.on('change', callback);
};
return Store;
}()); DeLorean.Flux = {createStore generates a store based on the definition
createStore: function (definition) {
/* store parameter must be an `object` */
if (typeof definition !== 'object') {
throw 'Stores should be defined by passing the definition to the constructor';
}extends the store with the definition attributes
var Child = function () { return Store.apply(this, arguments); };
var Surrogate = function () { this.constructor = Child; };
Surrogate.prototype = Store.prototype;
Child.prototype = new Surrogate();
__extend(Child.prototype, definition);
return new Child();
},createDispatcher generates a dispatcher with actions to dispatch.
/* `actionsToDispatch` should be an object. */
createDispatcher: function (actionsToDispatch) {
var actionsOfStores, dispatcher, callback, triggers, triggerMethod;If it has getStores method it should be get and pass to the Dispatcher
if (typeof actionsToDispatch.getStores === 'function') {
actionsOfStores = actionsToDispatch.getStores();
}
/* If there are no stores defined, it's an empty object. */
dispatcher = new Dispatcher(actionsOfStores || {});
/* Now call `registerAction` method for every action. */
for (var actionName in actionsToDispatch) {
if (__hasOwn(actionsToDispatch, actionName)) {
/* `getStores` & `viewTriggers` are special properties, it's not an action. Also an extra check to make sure we're binding to a function */
if (actionName !== 'getStores' && actionName !== 'viewTriggers' && typeof actionsToDispatch[actionName] === 'function') {
callback = actionsToDispatch[actionName];
dispatcher.registerAction(actionName, callback.bind(dispatcher));
}
}
}
/* Bind triggers */
triggers = actionsToDispatch.viewTriggers;
for (var triggerName in triggers) {
triggerMethod = triggers[triggerName];
if (typeof dispatcher[triggerMethod] === 'function') {
dispatcher.on(triggerName, dispatcher[triggerMethod]);
} else {
if (console != null) {
console.warn(triggerMethod + ' should be a method defined on your dispatcher. The ' + triggerName + ' trigger will not be bound to any method.');
}
}
}Allow only a single dispatcher
if (DeLorean.dispatcher != null) {
if (console != null) {
console.warn('You are attempting to create more than one dispatcher. DeLorean is intended to be used with a single dispatcher. This latest dispatcher created will overwrite any previous versions.');
}
}Create an internal reference to the dispathcer instance. This allows it to be found by the mixins.
DeLorean.dispatcher = dispatcher;
return dispatcher;
},DeLorean.Flux.defineIt’s a key to hack DeLorean easily. You can just inject something you want to define.
define: function (key, value) {
DeLorean[key] = value;
}
};Store and Dispatcher are the only base classes of DeLorean.
DeLorean.Dispatcher = Dispatcher;
DeLorean.Store = Store; DeLorean.Flux.mixins = {It should be inserted to the React components which
used in Flux.
Simply mixin: [Flux.mixins.storeListener] will work.
storeListener: {
trigger: function () {
this.__dispatcher.emit.apply(this.__dispatcher, arguments);
},After the component mounted, listen changes of the related stores
componentDidMount: function () {
var self = this, store, storeName;
/* `__changeHandler` is a **listener generator** to pass to the `onChange` function. */
function __changeHandler(store, storeName) {
return function () {
var state, args;
/* If the component is mounted, change state. */
if (self.isMounted()) {
self.setState(self.getStoreStates());
}When something changes it calls the components storeDidChanged method if exists.
if (self.storeDidChange) {
args = [storeName].concat(Array.prototype.slice.call(arguments, 0));
self.storeDidChange.apply(self, args);
}
};
}Remember the change handlers so they can be removed later
this.__changeHandlers = {};
/* Generate and bind the change handlers to the stores. */
for (storeName in this.__watchStores) {
if (__hasOwn(this.stores, storeName)) {
store = this.stores[storeName];
this.__changeHandlers[storeName] = __changeHandler(store, storeName);
store.onChange(this.__changeHandlers[storeName]);
}
}
},When a component unmounted, it should stop listening.
componentWillUnmount: function () {
for (var storeName in this.__changeHandlers) {
if (__hasOwn(this.stores, storeName)) {
var store = this.stores[storeName];
store.listener.removeListener('change', this.__changeHandlers[storeName]);
}
}
},
getInitialState: function () {
var self = this, state, storeName;
/* The dispatcher should be easy to access and it should use `__findDispatcher`
method to find the parent dispatchers. */
this.__dispatcher = __findDispatcher(this);If storesDidChange method presents, it’ll be called after all the stores
were changed.
if (this.storesDidChange) {
this.__dispatcher.on('change:all', function () {
self.storesDidChange();
});
}Since dispatcher.stores is harder to write, there’s a shortcut for it.
You can use this.stores from the React component.
this.stores = this.__dispatcher.stores;
this.__watchStores = {};
if (this.watchStores != null) {
for (var i = 0; i < this.watchStores.length; i++) {
storeName = this.watchStores[i];
this.__watchStores[storeName] = this.stores[storeName];
}
} else {
this.__watchStores = this.stores;
if (console != null && Object.keys != null && Object.keys(this.stores).length > 4) {
console.warn('Your component is watching changes on all stores, you may want to define a "watchStores" property in order to only watch stores relevant to this component.');
}
}
return this.getStoreStates();
},
getStoreStates: function () {
var state = {stores: {}}, store;
/* Set `state.stores` for all present stores with a `setState` method defined. */
for (var storeName in this.__watchStores) {
if (__hasOwn(this.stores, storeName)) {
state.stores[storeName] = this.__watchStores[storeName].getState();
}
}
return state;
},getStore is a shortcut to get the store from the state.
getStore: function (storeName) {
if (console != null && typeof this.__watchStores[storeName] === 'undefined') {
var message;
message = 'Attempt to getStore ' + storeName + ' failed. ';
message += typeof this.stores[storeName] === 'undefined' ? 'It is not defined on the dispatcher. ' : 'It is not being watched by the component. ';
message += this.constructor != null && this.constructor.displayName != null ? 'Check the ' + this.constructor.displayName + ' component.' : '';
console.warn(message);
}
return this.state.stores[storeName];
}
}
}; if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
var requirements = require('./requirements');
for (var requirement in requirements) {
DeLorean.Flux.define(requirement, requirements[requirement]);
}
module.exports = DeLorean;It can be also used in AMD projects, too.
And if there is no module system initialized, just pass the DeLorean
to the window.
} else {
if (typeof define === 'function' && define.amd) {
define(['./requirements.js'], function (requirements) {Import Modules in require.js pattern
for (var requirement in requirements) {
DeLorean.Flux.define(requirement, requirements[requirement]);
}
return DeLorean;
});
} else {
window.DeLorean = DeLorean;
}
}
})({});