Reputation: 344
I am trying to understand how to use requirejs and I am already stuck to a very simple task. How to I call a function defined inside require function and if this is the correct way of doing it.
example
require(['something'], function(something)
{
function hello_world()
{
alert('hello world');
}
});
Now how do I call the function hello_world from another file or from inside my html document. Obviously calling hello_world() returns undefined error.
I've start reading about the define method but if I understand correct, for every function I want to have, it must be in an external file?
Thank you.
EDIT Also I tried this one
define('hello_world', function(){
var hello_world = function()
{
alert('hello world');
};
return
{
hello_world: hello_world;
}
});
EDIT 2 - A maybe more practical example
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);
}
});
Upvotes: 0
Views: 1062
Reputation: 12275
You can't do that. In fact, modules and the whole idea of encapsulation is designed so you can't do things like that.
If you need to call hello_world from another module, you should define it as a module:
define('hello world', ['something'], function(something) {
return function hello_world() {
alert('hello world')
}
})
And then specify it as a dependency:
require(['hello world'], function(hello_world) {
hello_world()
})
Upvotes: 1