Search code examples
javascriptodoo

How to run a function from an imported object?


I'm working with an odoo application. And I'm trying to implement a JavaScript (native) module to extend the functionality of an existing service.

So in file_a.js I have the following (mock code):

function parentFunction(someArg) {
  function _internalFunction() {
    const someValue = 'some_value';
    return typeof someValue;
  }
}
export const mainAction = {
  dependencies: ['thingOne', 'thingTwo'],
  mainFunction(someArg) {
    return parentFunction(someArg);
  },
};
registry.category('services').add('action', mainAction); // this part is real code

In file_b.js, I'm importing the file_a as follows:

import { mainAction } from 'path/to/file_a';

console.log(typeof mainAction)
// output of above is object
for (const [key, value] of Object.entries(mainAction)) {
  console.log(`${key}: ${typeof value}`);
}
// output of for loop above is: dependencies: object / mainFunction: function
// at this point I know "mainFunction" is a function

What I'm stuck with is 2 things:

  1. How do I access what is being returned by mainFunction? In this case it would be parentFunction.
  2. Once I have access to parentFunction, how do I access _internalFunction?

What I'm trying to accomplish is to get the value of someValue inside of _internalFunction.

Hopefully this makes sense. Thank you all.


Solution

  • The only one thing should be changed in this code to get access to the internal function:

    1. The mainAction.mainFunction() will return you a result of the execution of parentFunction, in the current implementation it will be undefined since parentFunction doesn't return anything.
    2. To access the _internalFunction, you should return it from the parent function, like this:
    function parentFunction(someArg){
       return function _internalFunction(){
          const someValue = 'some_value';
          return typeof someValue;
       }
    }
    

    After this change, you are able to access the internal function:

    const internalFunction = mainAction.mainFunction()
    internalFunction() // string