【问题标题】:Why is 'this' in a Meteor Template onRendered Function undefined?为什么流星模板 onRendered 函数中的“this”未定义?
【发布时间】:2015-05-10 19:41:31
【问题描述】:

我正在使用流星 0.6.4。我遇到的问题是渲染模板时的数据上下文有时是未定义的,因此“this”对象是对 Window 的引用:

Template.task.time_left = function(){
    debugger;
    var nDate = this.due_date.getTime();

Exception from Deps recompute: TypeError: Cannot call method 'getTime' of undefined

html 代码包含在 {{each}} 句柄语句中:

<template name="tasks_lists">
    {{#each tasks_list}}
    ...
        {{#each task}}
            {{> task}}
        {{/each}}
    ...
    {{/each}}
</template>
<template name="task">
...
    <div class="text">{{due_date}}</div>
...
</template>

我读到这个错误已在早期版本的 Meteor 中解决。我能做些什么来避免使用“this”作为窗口调用的函数。

【问题讨论】:

    标签: meteor this


    【解决方案1】:

    您应该改用 template.xxx.helpers,即:

    Template.task.helpers({
      nDate: function() {
        return this.due_date.getTime();
      }
    });
    

    当您在帮助程序中使用它时,这就是数据上下文。

    【讨论】:

      【解决方案2】:

      我使用了“助手”功能,但遇到了同样的问题。 'this' 对象有时是窗口对象:

      Template.task.helpers({
      ...
          'time_left': function(){
              debugger;
              var nDate = this.due_date.getTime();
      ...
      

      【讨论】:

        【解决方案3】:

        当使用三个 Meteor 模板回调函数中的任何一个时,包括onRendered 函数,this 对象实际上是一个模板实例对象。虽然可以通过该对象检索模板的数据上下文,但建议您通过使用Template.currentData()函数来引用模板数据上下文。这个函数的文档可以在here找到。

        【讨论】:

          【解决方案4】:

          模板助手中的this 将始终指向window 对象。

          您可以访问Template.rendered() 中的data 上下文或事件处理函数。在事件处理程序中,它作为function( event, template ) 的第二个参数传递,其中template 是当前模板对象。

          不过我建议你使用模板实例函数如find(), findAll(), firstNode(), lastNode() 而不是数据上下文。

          Template.task.rendered = function() {
             if( !this.window ){     //check that 'this' is not a 'window' object
                var el = this.find( 'div.text' );  // the div that holds due_date
                //do something 
             }
          }
          

          【讨论】:

          • 模板onRendered回调函数内的this对象是对与该函数关联的模板实例的引用。有关onRendered 模板回调函数的更多详细信息,请参阅Meteor documentation
          猜你喜欢
          • 1970-01-01
          • 2017-10-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 1970-01-01
          • 2016-06-30
          • 2016-11-30
          相关资源
          最近更新 更多