But now I have to copy and paste one of those code-blocks for each template I use a dropdown in.
Isn’t there a way to make this work globally (like in a $(document).ready function above)?
For example why isn’t something like this working?
Templates render all the time during the app life cycle. So there could not be a global onRendered that is only called once. The solution to your problem is to put this into the templates that have dropdowns:
Note, that I use this.$. This will only find dropdowns in you template instead of all dropdowns on your page. I usually initialize each dropdown separately to pass different options if needed.
One thing that I’ve already done is create an array of templates like:
['template1', 'template2', 'template3']
And then, for each item create a rendered callback, like this:
myTemplates.forEach ( function (template) {
Template[template].onRendered();
}
That was easier to me to remeber, because it was a setting on project.
Another thing that you can try is to use this:
Meteor.startup(function(){
for(var property in Template){
// check if the property is actually a blaze template
if(Blaze.isTemplate(Template[property])){
var template=Template[property];
// assign the template an onRendered callback who simply prints the view name
template.onRendered(function(){
console.log(this.view.name);
});
}
}
});
I just wanted to point out that the answer @moretti gave was great. Note that he uses this.view.name rather than the “property”. If you do this, it won’t work since JavaScript is function scoped not block scoped, so you’ll be referencing the last value set to property at the end of the look, since onRendered() is asynchronous. I ended up using a functional each loop to avoid ever referencing the name from a previous loop: