简体   繁体   中英

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

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
    }

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 .

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

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
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM