繁体   English   中英

如何调用“定义”内部的JavaScript函数 - 匿名方法

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

如何在同一个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
    }

按照Dojo文档。 define块定义了一个模块。 您没有指定模块ID(可以显式传递或从文件名推断),因此我将继续进行,就像模块名为my/Example

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

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

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

1)将所有代码放在define / require中2)将其分成两个模块

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

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

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

如果它应该只是_testMethodInside方法和testMethodOutside函数的testMethodOutside函数,请考虑以下内容:

function sharedFunction() {
    return 'success';
}

function testMethodOutside() {
    sharedFunction();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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