问题
I know one is a reactive source, while the other is not. But I thought they would always give the same value.
Then I found the following code in Telescope's source:
var newTerms = Template.currentData().terms; // ⚡ reactive ⚡
if (!_.isEqual(newTerms, instance.data.terms)) {
instance.postsLimit.set(instance.data.terms.limit || Settings.get('postsPerPage', 10));
}
link: https://github.com/TelescopeJS/Telescope/blob/master/packages/telescope-posts/lib/client/templates/posts_list/posts_list_controller.js#L33
So it seems these two values can sometimes differ. When?
回答1:
According to Meteor's documentation, about template.data:
This property provides access to the data context at the top level of the template. It is updated each time the template is re-rendered. Access is read-only and non-reactive.
Since we know that the current data context is reactive, hence can change without the template being re-rendered (which is what makes reactivity look all nice and smooth on Blaze), this if statement is written to check if the "real" current terms (which are stored in the reactive Template.currentData()) have changed compared to the "previous" terms we had the last time the current template was rendered. (stored in the non-reactive template.data)
To wrap it up, what this autorun does is:
- Anytime the current data context changes...
- Fetch the terms from said data context
- Compare these terms to the ones stored in
template.datawhen the template was rendered - If they differ, that means the terms have changed (duh): reset the post limit.
回答2:
Within post_list_controller.js in the Template.onCreated() there is a section with:
// initialize the reactive variables
instance.terms = new ReactiveVar(instance.data.terms);
This reactive variable obtains it's terms value through:
{{> Template.dynamic template=template data=data}} // see posts_list_controller.html
Whenever you pass that template twice with a different set of data (David Weldon - scoped-reactivity), that reactive variable will be set and will cause the autorun to run.
// this part will cause the autorun to run
var terms = Template.currentData().terms; // ⚡ reactive ⚡
来源:https://stackoverflow.com/questions/32505601/when-do-template-currentdata-and-template-data-differ-in-value