【问题标题】:How to create a template helper after a template has been rendered in Meteor?在 Meteor 中渲染模板后如何创建模板助手?
【发布时间】:2014-07-23 16:59:58
【问题描述】:
Template.prices.rendered = function() {

  OrderFormContent = new Meteor.Collection(null);

  var orderSubmission = function() {
    //code that inserts stuff into the OrderFormContent collection
    //the key **sqft** is assigned the value of **4000**   };

  orderSubmission();

};

Template.prices.helpers({ 
  sqft: function() {
    return OrderFormContent.findOne().sqft;   
  } 
});

上面的代码没有加载。 Meteor 尝试创建 {{sqft}} 的助手,但不能因为 OrderFormContent 直到页面呈现后才被定义。看来 Meteor 试图在页面渲染之前定义帮助器。

但我需要定义这个助手。而且我只需要在模板渲染(而不是创建)之后定义它。

我不能只将Template.prices.helpers 嵌套在Template.prices.rendered 中。

澄清:

如果我注释掉 Template.prices.helpers 代码,页面将加载。如果我随后在控制台中手动运行OrderFormContent.findOne().sqft,则返回值 4000。

当我取消注释 Template.prices.helpers 代码时,页面无法加载,我收到 Exception from Deps recompute function: ReferenceError: OrderFormContent is not defined 错误。

【问题讨论】:

  • 为什么?从您发布的代码中,我看不出您以后要定义帮助程序的任何原因。
  • 什么意思?在定义 {{sqft}} 助手时,OrderFormContent 集合不存在。所以 Meteor 抛出一个错误,说 OrderFormContent 是未定义的,页面甚至没有加载。

标签: meteor


【解决方案1】:

1) 在函数内部定义全局变量是违反 Javascript 的良好实践的,在严格模式下是无效的(因此将来当严格模式成为标准时也会无效)。

2)您可以轻松实现您的目标,而无需在渲染后定义助手。实际上,创建帮助程序时不会抛出错误,而是在调用它时抛出错误。要解决此问题,只需进行简单检查即可。

var OrderFormContent = null;
var orderFormContentDep = new Deps.Dependency();

Template.prices.rendered = function() {
  OrderFormContent = new Meteor.Collection(null);
  ...
  orderFormContentDep.changed();
};

Template.prices.helpers({
  sqft: function() {
    orderFormContentDep.depend();
    if(!OrderFormContent) return null;
    var item = OrderFormContent.findOne();
    if(!item) return null;
    return item.sqft;
  });
});

【讨论】:

  • OrderFormContent 未定义,当我使用此代码时,帮助程序不返回任何内容。助手应该返回4000
  • 重新迭代,如果我注释掉Template.prices.helpers,页面加载和OrderFormContent.findOne().sqft 工作并返回4000,当我在页面完成加载后从控制台调用它时。但是当我将这个确切的代码放入Template.prices.helpers 时,页面不再加载,它说集合OrderFormContent 没有定义。
  • 对,你需要手动添加反应性到片断。我在示例中添加了 orderFormContentDep 依赖项,它现在应该会自行刷新。
【解决方案2】:

当我收到该错误时,我将模板帮助程序移至客户端 js,然后它就消失了。只是这对我的目的不起作用,因为它执行得太频繁了。因此,我将其放入 Iron Router 路由方法中进行渲染。

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 2015-01-06
    • 2015-01-15
    • 2014-07-14
    • 2013-04-25
    • 1970-01-01
    • 2014-11-27
    • 2013-02-18
    相关资源
    最近更新 更多