RedBrogdon
RedBrogdon

Reputation: 5351

What is the correct way to create variables in a meteor package that can be depended upon elsewhere?

I'm building a meteor package (mainly for my own use), and I would like for it to expose some readonly properties on which calculations outside the package can depend. My package's main js file looks roughly like this:

MyPackage = (function() {
  var prop1, prop2, myPackage = {};

  function setProp1(val) { prop1 = val; }
  function setProp2(val) { prop2 = val; }

  myPackage.publicMethod = function () {
    // This might change prop1 and prop2 via the setters as a side effect
  };

  myPackage.getProp1 = function() { return prop1; };
  myPackage.getProp2 = function() { return prop2; };

  return myPackage;
}();

The MyPackage object is exported using api.export, and functions as a sort of module.

I would like to be able to define a helper function in some template somewhere that reacts to changes in the values of prop1 and prop2, but still maintain their isolation behind the getter methods getProp1 and getProp2. What's the best way to do this?

I've read through the docs section on Deps.Dependency -- do I just need to architect my getters and internal setters using depend() and changed(), or is there something that has to happen in the package.js file?

Upvotes: 1

Views: 143

Answers (1)

sbking
sbking

Reputation: 7680

Yes, just use Deps.Dependency objects:

MyPackage = (function() {
  var prop1, prop2, myPackage = {};
  var prop1Dependency = new Deps.Dependency();
  var prop2Dependency = new Deps.Dependency();

  function setProp1(val) {
    prop1 = val;
    prop1Dependency.changed();
  }
  function setProp2(val)  {
    // alternatively:
    if (prop2 !== val) {
      prop2 = val;
      prop2Dependency.changed();
    }
  }

  myPackage.publicMethod = function () {
    // This might change prop1 and prop2 via the setters as a side effect
  };

  myPackage.getProp1 = function() {
    prop1Dependency.depend();
    return prop1;
  };
  myPackage.getProp2 = function() {
    prop2Dependency.depend();
    return prop2;
  };

  return myPackage;
}();

Then any helpers which call your getters will implicitly depend on the dependencies and react to changes made via the setters:

UI.registerHelper('prop1', function() {
  return MyPackage.getProp1();
});
Template.someTemplate.prop2 = function() {
  return MyPackage.getProp2();
};

You may also need to add this to your package.js in your on_use handler:

api.use("deps");

Upvotes: 3

Related Questions