About onCreated, onRendered, onDestroyed, and helpers

(bringing this topic from the ancient Google group)

So right now (on devel) you have the following methods available:

Template.name.onCreated
Template.name.onRendered
Template.name.onDestroyed
Template.name.helpers

You can add additional helpers in the onCreated event but you cannot add additional onRendered functions. What’s the rationale for this?

I have a package where I want the user to be able to do the following:

Template.home.onCreated({
  this.prepareTemplate();
});

And then the package adds the appropriate helpers, it sets something to be done when the template is rendered, and then some cleanup when the template is destroyed.

Is there a way to do this?

As I understand it, right now I can only add the appropriate helpers so the user has to add the rest of the boilerplate code “by hand”:

Template.home.onCreated({
  this.initializeAndAddHelpers();
});

Template.home.onRendered({
  this.doOnRenderedActions();
});

Template.home.onDestroyed({
  this.doOnDestroyedActions();
});

This is clunky, error prone and simply unnecessary (the user having to do a repetitive ceremony when the package could take care of it).

2 Likes

Why not just have your package work like this:

// Adds any callbacks and helpers you want to Template.name
Template.name.prepareTemplate()

@sashko I think in the user’s example, this is a template instance, and in your version it will be a template?

Yes, but prepareTemplate could add an onCreated callback to add whatever it wants to the template instance, right? Maybe there is something stopping that, in which case we should fix it.

That works for my purposes. I would then have to accept a function with a data parameter. On created I’ll pass this.data to the function so the user can give me the right object.

Template.home.prepareTemplate(function (data) {
    return { name: data.name, age: data.age };
});

if you use setTimeout it’s advisable to Meteor.setTimeout

The second example works because onRendered is slightly misleading, while the template has bee put in the DOM, its child elemnts could still be being rendered

should also work with 0 in the timer

Meteor.setTimeout(function(){
    $('#time_custom_scroll').mCustomScrollbar({
        setHeight: 244,
        mouseWheel:{
            enable: true,
            axis: "y"
        }
    });
}, 0)

I haven’t tested this, because I try not to trigger jquery in this way, but this might work because it requires the template instance

this.$('#time_custom_scroll').mCustomScrollbar({
    setHeight: 244,
    mouseWheel:{
        enable: true,
        axis: "y"
    }
});