-2

I'm a Java programmer who's trying to convert some Applets into JavaScript. I have a case with lots of small Java classes, which have a cohesive design that I'd like to keep if possible in JavaScript. RequireJS seems like a great way to keep it modular.

However, all the tutorials for requireJS I've seen treat a module as only having a single function, which only works for a couple of my Java classes. For example, this tutorial defines the module purchase.js as having a single function purchaseProduct():

define(["credits","products"], function(credits,products) {

  console.log("Function : purchaseProduct");

  return {
    purchaseProduct: function() {

      var credit = credits.getCredits();
      if(credit > 0){
        products.reserveProduct();
        return true;
      }
      return false;
    }
  }
});

Is there a way to allow more than one function per module in this way? In my head, a module is not necessarily just one function.

Or is RequireJS the wrong tree to be barking up for preserving my modular design from Java?

Edit

I found a much more useful set of examples for transitioning from Java to JS with requireJS at https://gist.github.com/jonnyreeves/2474026 and https://github.com/volojs/create-template

Fuhrmanator
  • 11,459
  • 6
  • 62
  • 111

2 Answers2

2

Yes, there's a way and it's very simple.

See, what you're returning (the module) is simply an object. In your code, this object has 1 property (purchaseProduct), but it can have as many as you'd like. And they don't all have to be functions either:

return {
  purchaseProduct: function () {/*...*/},
  returnProduct: function () {/*...*/},
  discountLevel: 0.25
};
Amit
  • 45,440
  • 9
  • 78
  • 110
1

Just add more functions to the object you return:

return {
  purchaseProduct: function() {
      // ...
  },
  somethingElse: function () {
      // ...
  }
}

If you return this as the value of your module, you'll have a module that exports two functions purchaseProduct and somethingElse.

Louis
  • 146,715
  • 28
  • 274
  • 320