簡體   English   中英

如何調用內部需求的函數

[英]how to call a function which is inside require

我正在嘗試了解如何使用requirejs,而我已經堅持了一個非常簡單的任務。 如何調用在require函數內部定義的函數,以及這是否是正確的方法。

require(['something'], function(something)
{

  function hello_world()
  {
    alert('hello world');
  }

});

現在如何從另一個文件或從html文檔中調用函數hello_world。 顯然,調用hello_world()會返回未定義的錯誤。

我已經開始閱讀有關define方法的信息,但是如果我理解正確的話,對於我想擁有的每個函數,它都必須位於外部文件中?

謝謝。

編輯我也嘗試過這個

define('hello_world', function(){
  var hello_world = function()
  {
    alert('hello world');
  };

  return
  {
    hello_world: hello_world;
  }
});

編輯2-一個也許更實際的例子

HTML

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script data-main="../scripts/test" src="../lib/require.js"></script>
</head>
<body>

  <svg width="400" height="100">
    <circle cx="24" cy="24" r="24"></circle>
    <circle cx="104" cy="64" r="24"></circle>
    <circle cx="184" cy="24" r="24"></circle>
  </svg>
  <br/>

  <a href='#' onclick="change_attributes">Change Attributes</a>

</body>
</html>

JS

requirejs.config({
    enforceDefine: false,
    paths: {
        d3: [
            '//d3js.org/d3.v3.min',
            '../lib/d3.min'
        ]
    }
});

require(['d3'], function (d3)
{
  // Selecting items
  var circles = d3.selectAll('circle');

  /*function change_attributes()
  {
    circles.style('fill', '#CF0000').attr('cy', 48);
  }*/

  function print_info(info)
  {
    info_screen.innerHTML = info;
  }

});


define('change_attributes', ['d3'], function(d3) {
    return function change_attributes() {
        circles.style('fill', '#CF0000').attr('cy', 48);
    }
});

你不能那樣做。 實際上,模塊和整個封裝的思想都是經過設計的,因此您不能做類似的事情。

如果需要從另一個模塊調用hello_world,則應將其定義為一個模塊:

define('hello world', ['something'], function(something) {
    return function hello_world() {
        alert('hello world')
    }
})

然后將其指定為依賴項:

require(['hello world'], function(hello_world) {
    hello_world()
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM