How to call a JavaScript function that is inside a "define" - anonymous method

416 Views Asked by At

How to call a function which is defined inside an anonymous function but both in the same JS file. Here is my code snippet. How to call _testMethodInside() from testMethodOutside()?

// Line 1 to 13 is an existing code from ESRI API
    define([
        "dojo/_base/declare",
        "dojo/_base/html"
    ], function (
        declare,
        html
    ) {
        return declare([_WidgetBase, _TemplatedMixin], {
            _testMethodInside: function () {
                return 'success';
            }
        });
    });

//Call above using this function
    function testMethodOutside(){
        //How to call _testMethodInside() function from here
    }
3

There are 3 best solutions below

0
On

Follow the Dojo documentation. The define block defines a module. You did not specify the module id (which would either be passed explicitly or inferred from the file name), so I will proceed as if the module is named my/Example.

require(['my/Example'], function(Example) {
   var example = new Example();
   example._testMethodInside(); // here is where you call _testMethodInside
}

The key thing is that because the module is loaded asynchronously, the only place you can safely call it from is the callback function you pass into (AMD) require.

0
On

With esri's Web app builder you'd usually either :

1) Have all your code inside the define/require 2) Separate it into two modules

That's just how the design of the flow is supposed to go, for example :

file1.js :

define([
    "dojo/_base/declare",
    "dojo/_base/html"
], function (
    declare,
    html
) {
    return declare([_WidgetBase, _TemplatedMixin], {
        _testMethodInside: function () {
            return 'success';
        }
    });
});

file2.js :

  require([
        './file1'
  ], function (File1) {

      File1._testMethodInside();
  })

Also, method names starting with an underline is a common design choice to designate private methods, so _testMethodInside should only really be called by file1

0
On

If it should be just a common function for the _testMethodInside method and testMethodOutside function, consider the following:

function sharedFunction() {
    return 'success';
}

function testMethodOutside() {
    sharedFunction();
}

define([
    "dojo/_base/declare",
    "dojo/_base/html"
], function (declare, html) {
    return declare([_WidgetBase, _TemplatedMixin], {
        _testMethodInside: sharedFunction
    });
});