如何将DOM属性与Mongo Collection中的每个项相关联

时间:2015-03-13 13:12:53

标签: meteor

如何为Meteor中的Mongo Collection中的每个项目提供一些HTML属性?我的用例是:

  • 我有一组文件(pdfs)
  • 我想为每个人显示一个拇指
  • 在模板上,每个文档都是一个绝对定位的article.document
  • 我想为" top"分配一个Math.random()值。和"左"对于每个article.document

我的代码:http://meteorpad.com/pad/bq6Ph5CQXMMejFQiF/DocumentList

文档list.html:

<template name="documentList">
    {{#each documents}}
      <article class="document {{#if active}}active{{/if}}">
        <header class="document-header">
          <div class="document-avatar btn-floating lighten-3"></div>
        </header>
      </article>
    {{/each}}
</template>

文档list.js:

Template.documentList.helpers({
  documents: function() {
    return Documents.find({});
  }
});

我的疑问是:我应该在哪里计算article.document元素的随机值,何时应该将值分配给DOM节点。

谢谢!

1 个答案:

答案 0 :(得分:1)

首先,您应该将文档模板分开:

<template name="documentList">
    {{#each documents}}
        {{> document}}
    {{/each}}
</template>

<template name="document">
  <article class="document {{#if active}}active{{/if}}">
    <header class="document-header">
      <div class="document-avatar btn-floating lighten-3"></div>
    </header>
  </article>
</template>

现在你可以创建一个渲染函数,为每个渲染到DOM中的文档调用它:

Template.document.rendered = function() {

  var $article = $(this.find('article'));

  // Add the position attributes etc. using JQuery

  $article.css({ 
    position: "absolute",
    top: 10, left: 10
  });
}
相关问题