onRenderd在Meteor中找不到元素

onRendered cannot find element in Meteor

本文关键字:找不到 元素 Meteor onRenderd      更新时间:2023-09-26

我有一个模板

{{#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"的元素,因为模板本身没有项目,因此在呈现模板时元素<ul id="myId">不存在。

我该怎么做才能确保元素在渲染时存在?

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

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

并在hasItems为 true 时包含此模板,然后对hasItems使用 onRendered 而不是外部模板。

但这不是有点丑陋的黑客吗?

这是你应该做的

模板

<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
  }
});