Meteor how to invoke client js function for only item added to Collection

With Meteor, I want new items that are added to a list to fade in. However, I don't want every element in the list to fade in slowly when something is added, only the new element that is added.

I have the following Collection published by the server and subscribed on the client

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


Meteor.autosubscribe(function () {
  Meteor.subscribe('list'); 
});

I have the following template:

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

<template name"list_item">
  {{ text }}
</template>

I would like to call the following when a new element is inserted into a Collection:

function (item) {
  var sel = '#' + item._id;
  Meteor.defer(function () {
    $(sel).fadeIn();
  });
}

I have tried using

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

However, the function is called for each item in the list when a new list_item is added, rather than only for the single new item.


I'm not sure you're supposed to call Meteor.defer directly, I couldn't find it in the docs. Also, the meteor versions of setTimeout and setInterval don't seem to be working properly and defer is just a wrapper around Meteor.setTimeout(fn(), 0) Anyway I got what I think you want working:

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>

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()
  }
}
链接地址: http://www.djcxy.com/p/58986.html

上一篇: TSQL中的多个LIKE语句

下一篇: 流星如何调用客户端js函数,仅用于添加到Collection中的项目