When do Template.currentData() and template.data differ in value?

怎甘沉沦 提交于 2019-12-22 04:38:11

问题


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:

  1. Anytime the current data context changes...
  2. Fetch the terms from said data context
  3. Compare these terms to the ones stored in template.data when the template was rendered
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!