Writing multiple functions in AMD javascript module

212 Views Asked by At

I am quite new to writing javascript code using AMD. I am stuck at figuring out how to write multiple functions in a file:

define(function(){
  return {
    and: function(a,b){
      return (a&&b);
    }
  };

}

);

I tried writing another function plus in the following way:

define(function(){
  return {
    plus: function(a,b){
      return (a+b);
    }
  };

}

);

But when I use grunt for testing, it is not able to detect the function plus

1

There are 1 best solutions below

1
On BEST ANSWER

You should place each module in it's own file. At least requireJS (are you using that?) determines the module name by it's file name (without the .js).

So a file sitting in /modules/A.js will have the module name "modules/A".

If you really want to define multiple modules in one file, you can do it in a more explicit way like this:

define("A", [], function () { return ...whatever... });
define("B", [], function () { return ...whatever... });

Edit:

for defining one module with two functions you can use different patterns. For a singleton (i.e. no "Class") I usually do something like this:

define(function () {
    var myModule = {
        fn1: function () { .... },
        fn2: function () { .... }
    };
    return myModule;
});