kadirahq / react-simple-di

Simple Dependancy Injection Solution for React
MIT License
56 stars 24 forks source link

Support nested actions #5

Open reohjs opened 8 years ago

reohjs commented 8 years ago

Hi,

I have a large app and find it beneficial to sometimes categorise the actions in my Mantra modules:

posts.list.created
posts.list.deleted
posts.admin.edit
// etc...

Possible implementation:

export function injectDeps(context, _actions) {
  const actions = {};

  function bindNested (obj) {
      var memo = {};
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (typeof obj[key] === 'object') {
            memo[key] = bindNested(obj[key]);
          } else {
            memo[key] = obj[key].bind(null, context);
          }
        }
      }
      return memo;
    }

    for (var key in _actions) {
      if (_actions.hasOwnProperty(key)) {
        var actionMap = _actions[key];
        var newActionMap = {};
        for (var actionName in actionMap) {
          if (actionMap.hasOwnProperty(actionName)) {
            var actionOrObj = actionMap[actionName];
            if (typeof actionOrObj === 'object') {
              newActionMap[actionName] = bindNested(actionOrObj);
            } else {
              newActionMap[actionName] = actionOrObj.bind(null, context);
            }
          }
        }
        actions[key] = newActionMap;
      }
    }
  // etc...

Let me know if you'd accept a PR for this :)