【问题标题】:How to call a JavaScript function that is inside a "define" - anonymous method如何调用“定义”内的 JavaScript 函数 - 匿名方法
【发布时间】:2018-11-29 21:41:26
【问题描述】:

如何调用定义在匿名函数内部但都在同一个 JS 文件中的函数。这是我的代码 sn-p。如何从testMethodOutside()调用_testMethodInside()

// 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
    }

【问题讨论】:

  • 为什么要实现这样的事情?
  • @BooBerr'ita,第 1 到 13 行是 ESRI API 的现有代码。我想使用我的testMethodOutside() 调用该方法
  • 这称为AMD format,是定义模块的一种流行方式。您可以将它们与require 一起使用,并且您应该有一个声明definerequire 的模块加载器库。

标签: javascript dojo amd js-amd esri-javascript-api


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    1) 将所有代码包含在定义/要求中 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 真正调用

    【讨论】:

      【解决方案3】:

      如果它只是_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
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-19
        • 2015-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多