Template 实例的created 和rendered 回调有什么区别? [英] What is the difference between created and rendered callback of Template instance?
问题描述
官方文档
[rendered] 在 Template.myTemplate 的实例被调用时调用一次渲染成DOM节点,第一次放入文档.
[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] 回调在评估模板的逻辑之前被调用第一次.
[created] callback is called before your template's logic is evaluated for the first time.
有点让我困惑.它们之间究竟有什么区别?一旦创建"模板实例,它们似乎都被调用.如果有,它们各自的用途是什么?附言我发现 Meteor 文档的很大一部分缺乏可靠的示例,这对于初学者来说确实很难理解.
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.
推荐答案
模板 rendered
回调在 DOM 呈现在屏幕上后触发.created
回调在模板已实例化但尚未呈现时触发.
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.
您可以使用 rendered
回调来更改页面上的任何内容.例如,如果您使用 select2
您需要将 选项转换为更好的 select2 版本,您可以执行此操作(您需要 select2 包,但任何 jquery 插件工作原理类似)
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({});
}
您不能在 .created
上执行此操作,因为尚未在 DOM 上绘制 select2.
You can't do this on .created
because the select2 would not yet have been drawn on the DOM.
您可以使用 .created
来设置任何变量.例如,如果您在页面上的某处使用 Session.get("myvalue")
,您可以使用 .created
在页面大约将被制作例如
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);
}
通常,渲染回调用于以某种方式操作 DOM.当它不是关于 DOM 而是关于管理变量或数据时,使用 created 回调.
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.
这里还有一些区别.
您将使用 .created &如果您使用每个模板订阅(最近添加到 Meteor),则不会 .rendered:
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");
}
您将使用 .rendered 来初始化谷歌地图
You would use .rendered to initialize google maps
Template.hello.rendered = function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {});
}
这篇关于Template 实例的created 和rendered 回调有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!