在铁路由器中,如何在仅更改子集时避免重新计算整个数据字段

时间:2014-04-26 07:48:24

标签: meteor iron-router

在Iron-router中,我们可以将数据传递到数据字段中的页面。例如:

Router.map(function () {
  this.route('myroute', {
    path: '/route',
    template: 'myTemplate',

    data: function () {
      return {
        title: getTitle(),
        description: getDescription(), 
      }
    }
  });
});

在模板中,标题和描述实际上是传递给子模板的一些值:

<template name="myTemplate">
  {{> titleTemplate title}}
  {{> descriptionTemplate description}}
</template>

由于铁路由器中的数据字段是被动的,因此每当会话变量发生变化时,都会重新计算数据字段。

但是,在这种情况下,getTitle函数中的会话变量只更改模板“titleTemplate”,而getDescription()函数中的会话变量只更改模板“descriptionTemplate”。

如果getTitle()函数中的会话变量发生了变化,我只想执行getTitle()函数,而不执行getDescription()函数。如果可能的话,我还想只渲染“titleTemplate”并且不渲染“descriptionTemplate”。

我想知道这是否可行。如果这不是编写Meteor应用程序的正确方法,那么更好的方法是什么?

感谢。

2 个答案:

答案 0 :(得分:3)

这是一个有趣的情况。尽管getTitlegetDescription函数可能依赖于完全不同的反应变量,但只要其中任何一个发生变化,它们都将被重新计算。

一种可能的解决方案是传递函数本身而不是调用函数的结果。取决于它们在子模板中的使用方式,这可能会也可能不方便,但它会阻止它们每次都运行。这是一个简单的例子:

<template name="myTemplate">
  {{> titleTemplate title}}
  {{> descriptionTemplate description}}
</template>

<template name="titleTemplate">
  <p>{{excitedTitle}}</p>
</template>

<template name="descriptionTemplate">
  <p>{{this}}</p>
</template>
var getTitle = function() {
  console.log('computed title');
  return Session.get('title');
};

var getDescription = function() {
  console.log('computed description');
  return Session.get('description');
};

Router.map(function() {
  this.route('home', {
    path: '/',
    template: 'myTemplate',
    data: function() {
      return {
        title: getTitle,
        description: getDescription
      };
    }
  });
});

Meteor.startup(function() {
  Session.setDefault('title', 'title1');
  Session.setDefault('description', 'description1');
});

Template.titleTemplate.excitedTitle = function() {
  return "" + (this.toUpperCase()) + "!";
};

在控制台中,您可以更改会话变量(titledescription),您将看到一次只能运行一个函数。我希望有所帮助。

答案 1 :(得分:0)

解决此问题的一种方法是使用data上下文,但只使用模板特定的帮助程序。由于我不知道您的getTitlegetDescription函数的作用,我无法判断这是否适合您。这取决于您是否需要在这些函数中使用this对象,并且需要this来引用路由对象。如果没有,那么以下似乎是更好的解决方案:

JS:

Router.map(function () {
  this.route('myroute', {
    path: '/route',
    template: 'myTemplate'
  });
});

Template.myTemplate.title = getTitle;
Template.myTemplate.description = getDescription;

HTML:

<template name="myTemplate">
  {{> titleTemplate title}}
  {{> descriptionTemplate description}}
</template>
相关问题