longshotlabs / meteor-template-extension

A Meteor package: Replace already defined templates, inherit helpers and events from other templates
https://atmospherejs.com/aldeed/template-extension
MIT License
220 stars 20 forks source link

Getting firstNode with Template.forEach(callback) #35

Closed SachaG closed 8 years ago

SachaG commented 9 years ago

I'm doing:

Template.onRendered(function () {
   console.log(this)
});

And:

Template.forEach(function (template) {
   console.log(template)
});

In the first case, the template has a firstNode property which can be used to manipulate its DOM element, but in the second case that property doesn't exist.

Is there a way to access it? Basically I'm trying to trigger a callback on all templates for arbitrary events (such as route changes), and not just once when they initially render.

(see: https://www.youtube.com/watch?v=7Ux4wxg7Kko)

aldeed commented 9 years ago

Did you figure this out?

Template.forEach loops through the defined templates (Blaze.Template instances), while onRendered will be for a single template instance (Blaze.TemplateInstance instance). I think you're asking to loop through all "currently rendered template instances".

So one way (untested) might be:

Template.forEachCurrentlyRenderedInstance(function (templateInstance) {
   console.log(templateInstance)
});

Which you could create with:

Template._renderedInstances = [];

Template.onRendered(function () {
  Template._renderedInstances.push(this);
});

Template.onDestroyed(function () {
  var i = Template._renderedInstances.indexOf(this);
  if (i > -1) {
    Template._renderedInstances.splice(i, 1);
  }
});

Template.forEachCurrentlyRenderedInstance = function (func) {
  Template._renderedInstances.forEach(func);
};

If it works, maybe we could add this to this package.

aldeed commented 8 years ago

Added Template.forEachCurrentlyRenderedInstance in 4.0