What is the difference between created and rendered callback of Template instance?
meteor
Solution
The template `rendered` callback is fired after the DOM is rendered on screen. The `created` callback is fired when the Template is instantiated but not yet rendered.
You can use the `rendered` callback to change anything on the page. For example if you use `select2` you need to convert a `<select>` option into a nicer select2 version you can do this (you need the select2 package, but any jquery plugin works similarly)
Template.hello.rendered = function() {
this.$("select").select2({});
}
You can't do this on `.created` because the select2 would not yet have been drawn on the DOM.
You can use `.created` to set up any variables. For example if you use a `Session.get("myvalue")` somewhere on the page, you could use `.created` to reset it to a default value when the page is about to be made e.g
Template.hello.created = function() {
Session.set("myvalue", null);
}
In general the rendered callback is used to manipulate the DOM in some way. The created callback is used when its not about the DOM but rather about managing variables or data.
Here are some more distinctions.
You would use .created & not .rendered if you use per template subscriptions (added very recently to Meteor):
Template.hello.created = function() {
this.subscribe("some_publication");
}
You would use .rendered to initialize google maps
Template.hello.rendered = function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {});
}
Problem
The official documentation [rendered] is called once when an instance of Template.myTemplate is rendered into DOM nodes and put into the document for the first time. [created] callback is called before your template's logic is evaluated for the first time. kind of confuses me. What exactly is the difference between them? They both seem to be called once a template instance is "created". If so, what are their respective usages? P.S. I find that a big portion of the Meteor documentation lacks solid examples, which is really hard for beginners to understand.