Meteor如何仅为添加到Collection的项调用客户端js函数

Jos*_*itt 7 meteor

使用Meteor,我希望添加到列表中的新项目淡入.但是,我不希望列表中的每个元素在添加内容时缓慢淡入,只需添加新元素.

我有以下由服务器发布并在客户端订阅的集合

List = new Meteor.Collection("List");


Meteor.autosubscribe(function () {
  Meteor.subscribe('list'); 
});
Run Code Online (Sandbox Code Playgroud)

我有以下模板:

<template name="list">
  {{#each list}}
    {{> list_item }}
  {{/each}}
</template>

<template name"list_item">
  {{ text }}
</template>
Run Code Online (Sandbox Code Playgroud)

将新元素插入到集合中时,我想调用以下内容:

function (item) {
  var sel = '#' + item._id;
  Meteor.defer(function () {
    $(sel).fadeIn();
  });
}
Run Code Online (Sandbox Code Playgroud)

我试过用

List.find().observe({
  added: function (list_item) {
    var sel = '#' + list_item._id;
    Meteor.defer(function() {
      $(sel).fadeIn();
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

但是,当添加新的list_item时,将为列表中的每个项调用该函数,而不是仅针对单个新项.

gre*_*reg 4

我不确定你是否应该直接调用 Meteor.defer,我在文档中找不到它。另外,setTimeout 和 setInterval 的流星版本似乎无法正常工作,并且 defer 只是一个包装无论如何,Meteor.setTimeout(fn(), 0)我得到了我认为你想要的工作:

html:

<body>
  {{> list_items}}
</body>

<template name="list_items">
  <ul>
    {{#each list_items}}
      <li id="list-item-{{_id}}" style="display:none;">
        {{text}}
      </li>
    {{/each}}
  </ul>
</template>
Run Code Online (Sandbox Code Playgroud)

js:

List = new Meteor.Collection("List")

if (Meteor.is_client) {
  Meteor.subscribe("List")

  Meteor.autosubscribe(function(){
    List.find().observe({
      added: function(item){
        setTimeout("$('#list-item-"+item._id+"').fadeIn('slow')",10)
      }
    });
  });

  Template.list_items.list_items = function(){
    return List.find()
  }
}
Run Code Online (Sandbox Code Playgroud)