Call a function using requirejs

How do I call a function using requirejs?

This is too simple a question, but, surprisingly, not a single textbook or example has helped me so far.

This is the code in my html file.

...
<script src = "stuff.js"></script>
<button onclick="doStuff(4, 2)";>DoStuff</button>
...

This is my js request.

define(["jquery"], function ($) {
  function doStuff(a, b) {
    //does some stuff
  }
});

Why is this not working? I got ReferenceError: doStuff not defined

+4
source share
2 answers

I managed to find a solution to the issue by passing the function to the html code. It is not very elegant, but it works.

index.html

<button onclick = "doSomeStuff(4,2);">DoStuff</button>
<script>
  require(['stuff.min'], function(myStuff){
    function doSomeStuff(a,b) {
      myStuff.doStuff(a,b);
    }
  });
</script>

stuff.js

define(["jquery"], function ($) {
  function doStuff(a,b) {
    //does some stuff
  }
  return {doStuff:doStuff};
});
0
source

The answer to your immediate problem might be something like this:

index.html

<button id="the-button">DoStuff</button>
<script data-main="stuff" src="scripts/require.js"></script>

stuff.js

require(["jquery"], function ($) {
  function doStuff(a, b) {
    //does some stuff
  }

  $('#the-button').click(function() {
    doStuff(4, 2);
  });
});

, JavaScript. : onClick() HTML ?

+3

All Articles