【问题标题】:onRendered cannot find element in MeteoronRendered 在 Meteor 中找不到元素
【发布时间】:2016-02-09 19:25:25
【问题描述】:

我有一个模板

{{#if hasItems}}
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
{{else}}
  <p>No items</p>
{{/if}}

Template.itemList.onRendered( function () {
  var el = this.find( '#myId' );
} );

但是id="myId"的元素一直找不到,因为模板最初没有项目,所以在模板渲染时&lt;ul id="myId"&gt;元素不存在。

如何确保元素在渲染时存在?

我想我可以将var el = this.find( '#myId' ); 放入Tracker.autorun 或制作一个嵌套模板

<template name="hasItems">
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
</template>

并在hasItems 为真时包含此模板,然后将onRendered 用于hasItems 而不是外部模板。

但这不是有点难看吗?

【问题讨论】:

  • 如何订阅数据?您可以在 autorun 中使用 subscriptionsReady() 来了解何时加载数据。
  • 恕我直言,嵌套模板解决方案是要走的路;)
  • 正如@MarkUretsky 所说,您必须等待订阅准备就绪。你可以看看here

标签: javascript jquery node.js templates meteor


【解决方案1】:

这是你应该做的事情

模板

<template name="itemList">
  {{#if hasItems}}
    {{> showItems }}
  {{else}}
    <p>No items</p>
  {{/if}}
</template>

<template name="showItems">
  <ul id="myId">
    {{#each items}}
      {{> item}}
    {{/each}}
  </ul>
</template>

渲染处理程序

Template.itemList.helpers({
  hasItems: function() { 
    // do you have items? 
  }
});

Template.showItems.onRendered(function (){
  var el = this.find( '#myId' );
});

Template.showItems.helpers({
  items: function() { 
    // return the items
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多