meteor: template instance
In scoped reactivity we learned how templates can maintain their own reactive state. A common frustration with this technique is that Template.instance()
is pretty verbose. This is particularly noticeable when writing helpers like these:
Template.colorSquare.helpers({
currentColor: function() {
return Template.instance().currentColor.get();
},
colorCount: function() {
return Template.instance().colorCount.get();
},
isFancy: function() {
return Template.instance().isFancy.get();
}
});
Templates have direct access to their instance variables so we can remove all of the above and and instead write code like this:
<template name="colorSquare">
<div style="background: {{Template.instance.currentColor.get}}"></div>
</template>
It still seems excessive, but at least we've eliminated the helper functions. In order to save a few keystrokes, we recently added this global helper to the Edthena codebase:
Template.registerHelper('instance', function() {
return Template.instance();
});
Now the same template can be written like this:
<template name="colorSquare">
<div style="background: {{instance.currentColor.get}}"></div>
</template>
We like this pattern because it removes helpers and it makes the source of the data crystal clear.
Keep in mind that your implementation of the instance
helper could be more sophisticated or specialized. For example, it could take arguments behave differently depending on the type of variable being read. The possibilities are endless. Happy refactoring!