call a function using requirejs

好久不见. 提交于 2019-12-05 00:16:39

问题


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


回答1:


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?




回答2:


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


来源:https://stackoverflow.com/questions/20336455/call-a-function-using-requirejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!