WSkinner
WSkinner

Reputation: 2217

How to Cache a Javascript Class to be used as a require.js Dependency?

I want to create a javascript class definition wrapped in a require.js module that will be returned whenever that module is listed as a dependency of another module. It gets tricky when the class definition has dependencies of its own that need to be enclosed with it. This is the best approach I have come up with. Is there a better way?

define(
  ['js/myDependency']
  ,(function() {
    var myClass = void 0;

    return function(myDependency) {
      if(!myClass)
      {
        myClass = function MyClass(color) {
          this.state = 0;
          this.color = color;
        }

        MyClass.prototype.inputSomething = function(input) {
          this.state = myDependency.handleInput(input);
        }
      }

      return myClass;
    }

  })()
);

Upvotes: 1

Views: 157

Answers (1)

WSkinner
WSkinner

Reputation: 2217

After some research I've discovered my solution was unnecessarily complex. Require.js only calls the the callback passed to define once and then returns it's result to subsequent requests for the defined module. This works the same:

define(['js/myDependency'], function(myDependency) {
  function MyClass(color) {
    this.state = 0;
    this.color = color;
  }

  MyClass.prototype.inputSomething = function(input) {
    this.state = myDependency.handleInput(input);
  }

  return myClass;
});

Upvotes: 2

Related Questions