Skip to content

Commit

Permalink
Ability to module-namespace actions
Browse files Browse the repository at this point in the history
  • Loading branch information
markshust committed Jul 12, 2016
1 parent d461915 commit 334e881
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 9 deletions.
34 changes: 34 additions & 0 deletions src/__tests__/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ describe('App', () => {
expect(app.actions).to.be.deep.equal({bb: 10});
});

it('should merge actions if namespaced', () => {
const app = new App({});
app.actions = {core: {bb: 10}};
const module = {};

app.loadModule(module);
expect(app.actions).to.be.deep.equal({core: {bb: 10}});
});

describe('has module.load', () => {
it('should throw an error if module.load is not a function', () => {
const context = {};
Expand Down Expand Up @@ -110,6 +119,31 @@ describe('App', () => {

app.loadModule(module);
});

it('should call module.load with context and actions when namespaced', done => {
const context = {aa: 10};
const app = new App(context);
app.actions = {
core: {
hello: {
aa(c, a) {
expect(c).to.deep.equal(context);
expect(a).to.be.equal(20);
done();
}
}
}
};

const module = {
load(c, actions) {
expect(c).to.be.equal(context);
actions.core.hello.aa(20);
},
};

app.loadModule(module);
});
});

it('should mark the module as loaded', () => {
Expand Down
34 changes: 25 additions & 9 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,33 @@ export default class App {

_bindContext(_actions) {
const actions = {};
for (let key in _actions) {
if (_actions.hasOwnProperty(key)) {
const actionMap = _actions[key];
const newActionMap = {};
for (let actionName in actionMap) {
if (actionMap.hasOwnProperty(actionName)) {
newActionMap[actionName] =
actionMap[actionName].bind(null, this.context);

for (let namespace in _actions) {
if (_actions.hasOwnProperty(namespace)) {
actions[namespace] = {};
const namespaceActions = _actions[namespace];
for (var namespaceAction in namespaceActions) {
if (namespaceActions.hasOwnProperty(namespaceAction)) {
actions[namespace][namespaceAction] = {};
var actionFuncs = namespaceActions[namespaceAction];
var actionFuncsExist = false;
for (var actionFunc in actionFuncs) {
if (actionFuncs.hasOwnProperty(actionFunc)
&& typeof actionFuncs[ actionFunc ] === 'function'
) {
actions[namespace][namespaceAction][actionFunc]
= actionFuncs[actionFunc].bind(null, this.context);
actionFuncsExist = true;
}
}
if (! actionFuncsExist
&& actions.hasOwnProperty(namespace)
&& typeof actionFuncs === 'function'
) {
actions[namespace][namespaceAction] = actionFuncs.bind(null, this.context);
}
}
}
actions[key] = newActionMap;
}
}

Expand Down

0 comments on commit 334e881

Please sign in to comment.