2

如何调用在匿名函数内部但都在同一个 JS 文件中定义的函数。这是我的代码片段。如何拨打_testMethodInside()电话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
    }
4

3 回答 3

2

遵循Dojo文档。该define块定义了一个模块。您没有指定模块 ID(将显式传递或从文件名推断),因此我将继续处理,就好像模块名为my/Example.

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

关键是因为模块是异步加载的,所以唯一可以安全调用它的地方是传入(AMD)require的回调函数。

于 2018-12-04T04:05:13.857 回答
2

使用 esri 的 Web 应用程序构建器,您通常可以:

1) 将所有代码放在定义/要求中 2) 将其分成两个模块

这就是流程设计应该如何进行的,例如:

文件 1.js:

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

文件 2.js:

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

      File1._testMethodInside();
  })

此外,以下划线开头的方法名称是指定私有方法的常见设计选择,因此 _testMethodInside 应该只真正由 file1 调用

于 2018-12-04T16:34:16.247 回答
0

如果它应该只是_testMethodInside方法和testMethodOutside函数的通用函数,请考虑以下几点:

function sharedFunction() {
    return 'success';
}

function testMethodOutside() {
    sharedFunction();
}

define([
    "dojo/_base/declare",
    "dojo/_base/html"
], function (declare, html) {
    return declare([_WidgetBase, _TemplatedMixin], {
        _testMethodInside: sharedFunction
    });
});
于 2018-12-09T00:08:10.890 回答