From e2ee740942cd73acb0ec2aba5d8093c66fe695dc Mon Sep 17 00:00:00 2001 From: Mark Shust Date: Wed, 10 Aug 2016 12:00:49 -0400 Subject: [PATCH] Merged PR from https://github.com/kadirahq/react-simple-di/pull/7 --- lib/__tests__/index.js | 31 +++++++++++++++++++++++++++++++ lib/index.js | 33 +++++++++++++++++++++++++-------- 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/lib/__tests__/index.js b/lib/__tests__/index.js index 09a7fc2..37a8a75 100644 --- a/lib/__tests__/index.js +++ b/lib/__tests__/index.js @@ -62,6 +62,37 @@ describe('Depedancy Injection', () => { expect(el.html()).to.match(/arunoda-susiripala/); }); + it('should inject namespaced actions and allow to use them', () => { + const context = {name: 'arunoda'}; + const actions = { + core: { + default: { + getFullName({ name }, surname) { + return `${name}-${surname}`; + } + } + } + }; + const Layout = ({children}) => children; + const LayoutWithDeps = injectDeps(context, actions)(Layout); + + const Comp = ({getName}) => (

{getName('susiripala')}

); + const mapper = (c, a) => ({ + getName: a.core.default.getFullName + }); + const CompWithDeps = useDeps(mapper)(Comp); + + const el = shallow(( +
+ + + +
+ )); + + expect(el.html()).to.match(/arunoda-susiripala/); + }); + it('should let use inject actions multiple times', () => { const context = {name: 'arunoda'}; const actions = { diff --git a/lib/index.js b/lib/index.js index 9723aec..5e51310 100644 --- a/lib/index.js +++ b/lib/index.js @@ -7,16 +7,33 @@ const getDisplayName = Component => ( export function injectDeps(context, _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, context); + for (let namespace in _actions) { + if (_actions.hasOwnProperty(namespace)) { + actions[namespace] = {}; + let namespaceActions = _actions[namespace]; + for (let namespaceAction in namespaceActions) { + if (namespaceActions.hasOwnProperty(namespaceAction)) { + actions[namespace][namespaceAction] = {}; + let actionFuncs = namespaceActions[namespaceAction]; + let actionFuncsExist = false; + for (let actionFunc in actionFuncs) { + if (actionFuncs.hasOwnProperty(actionFunc) && + typeof actionFuncs[actionFunc] === 'function' + ) { + actions[namespace][namespaceAction][actionFunc] = + actionFuncs[actionFunc].bind(null, context); + actionFuncsExist = true; + } + } + if (!actionFuncsExist && + actions.hasOwnProperty(namespace) && + typeof actionFuncs === 'function' + ) { + actions[namespace][namespaceAction] = + actionFuncs.bind(null, context); + } } } - actions[key] = newActionMap; } }