简体   繁体   中英

Include javascript functions in dojo code

I have this js file that contains some functions, for example a file x.js .

I need to reuse the functions in x.js in other files so I don't write the same function twice. I tried the "dojo/request/script" but it doesn't work.

Is there any suggestion on how to import these functions?

Ideally, you should make the file into an AMD module. For example, if your my/AB.js contains this:

function f1(x) { /*..*/ }
function f2(y) { /*..*/ }

You should rewrite it to:

define([], function() {
  return {
    f1: function(x) { /*..*/ },
    f2: function(y) { /*..*/ }
  }
});

Then, in your other javascript file(s), you can use require to load it.

require(['my/AB'], function(AB) {
  AB.f1('foo');
  AB.f2('bar');
});

( Notice that there's no .js extension in my/AB !)

This has the benefit that your functions in AB.js are no longer in the global scope, ie they will not collide with other people's functions. It also allows you to use the Dojo build system to deploy optimized, combined files later on.

However, this is not always possible. Perhaps other JS files are relying on f1 and f2 being in the global scope. But you can load non-AMD, regular files with Dojo's loader too, by simply adding the .js extension.

require(['my/AB.js'], function() {
  window.f1('foo');
  window.f2('bar');
});

Note that in all these cases, I've assumed your code is in a directory called my . Whatever your actual directory is called, you need to tell the Dojo loader about it in the dojoConfig.

<script type="text/javascript">
  var dojoConfig = {
    baseUrl: ".....",
    // your other config parameters,
    packages: [ 'my', '../folder/relative/to/baseUrl/my' ]
  };
</script>
<!-- your inclusion of dojo.js somewhere below this -->

PS: You can actually load JS files from arbitrary locations too:

require(['http://example.com/js/my/AB.js'], function() {
  window.f1('foo');
  window.f2('bar');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM