如何调用内部需要的函数

时间:2014-02-20 12:49:40

标签: javascript function requirejs

我试图了解如何使用requirejs,我已经陷入了一个非常简单的任务。 如何调用require函数中定义的函数,如果这是正确的方法。

例如

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

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

});

现在如何从另一个文件或我的html文档中调用函数hello_world。显然,调用hello_world()会返回未定义的错误。

我开始阅读有关define方法的内容,但如果我理解正确,对于我想要的每个函数,它必须在外部文件中?

谢谢。

EDIT 我也试过这个

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

1 个答案:

答案 0 :(得分:1)

你做不到。事实上,模块和封装的整个想法是设计的,所以你不能做那样的事情。

如果你需要从另一个模块调用hello_world,你应该将它定义为一个模块:

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

然后将其指定为依赖项:

require(['hello world'], function(hello_world) {
    hello_world()
})
相关问题