7

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.

Josh Petitt
  • 9,371
  • 12
  • 56
  • 104
  • I have seen this that suggested observe: http://stackoverflow.com/questions/10274679/invoke-a-client-js-function-in-meteor-after-getting-results-from-the-server I've also seen this: http://stackoverflow.com/questions/10109788/callback-after-the-dom-was-updated-in-meteor-js However, with both methods, all elements are faded in, instead of only the last inserted element. – Josh Petitt Apr 25 '12 at 00:51
  • Have you found any solutions? – Alex Okrushko Dec 24 '12 at 19:48
  • No, although I haven't tried in months... – Josh Petitt Dec 27 '12 at 15:02

1 Answers1

4

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()
  }
}
greggreg
  • 11,945
  • 6
  • 37
  • 52