Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a function using requirejs

Tags:

html

requirejs

How do I call a function using requirejs?

It's an overly simple question, but surprisingly enough no tutorial or example has been able to help 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 require js.

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

Why does this not work? I get ReferenceError: doStuff is not defined

like image 950
user3037540 Avatar asked Dec 02 '13 19:12

user3037540


People also ask

Is RequireJS obsolete?

RequireJS has been a hugely influential and important tool in the JavaScript world. It's still used in many solid, well-written projects today.

What is RequireJS used for?

RequireJS is a JavaScript library and file loader which manages the dependencies between JavaScript files and in modular programming. It also helps to improve the speed and quality of the code.

How do I use require config?

RequireJS can be initialized by passing the main configuration in the HTML template through the data-main attribute. It is used by RequireJS to know which module to load in your application. To include the Require. js file, you need to add the script tag in the html file.

What is require () in JavaScript?

require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.


2 Answers

The answer to your immediate problem could 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);
  });
});

But it looks like you would benefit from taking a step back and reading about modern JavaScript architecture and techniques. This should be a good starting point: Why is using onClick() in HTML a bad practice?

like image 177
kryger Avatar answered Nov 15 '22 06:11

kryger


I managed to find a solution for the question by passing the function into the html code. It's 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};
});
like image 45
user3037540 Avatar answered Nov 15 '22 06:11

user3037540