k.chao.0424
k.chao.0424

Reputation: 1191

Meteor - apply same onRender code for multiple templates

I am trying to code with DRY principle. I have multiple templates that should share the same onRender code:

Template.cardA.onRendered(function () {
  coolLogic()
});
Template.cardB.onRendered(function () {
  coolLogic()
});

Is it possible for me to avoid having to repeat coolLogic()?

Upvotes: 0

Views: 123

Answers (2)

Christian Fritz
Christian Fritz

Reputation: 21384

Template is an object, so you can iterate its members:

_.each(["cardA", "cardB"], function(t) {
  Template[t].onRendered(function () {
    coolLogic()
  });
});

Upvotes: 1

halbgut
halbgut

Reputation: 2386

The only drier solution I can think of, is to drop the anonymous function around coolLogic.

Template.cardA.onRendered(coolLogic);
Template.cardB.onRendered(coolLogic);

Upvotes: 1

Related Questions