以最小的方式定期向客户显示记录

时间:2014-10-25 13:02:01

标签: meteor

我有一个名为books

的集合

在我的订阅中,我向客户发送了5条记录,

现在我想每隔3分钟向客户端显示一条记录

我试过这样的

on the helper I'm returning

Template.book.helpers({
    'book':function(){
          var books=Books.find({});
          books.forEach(function(book){
          setTimeout(function(){
               Session.set("currentBookId",book._id);
          },3*60*1000);
         });
         return Books.find({_id:Session.get("curentBookId")}); 
      }
})

这显示最后一条记录 我知道这不起作用,有人能建议我这样做的正确方法吗?

1 个答案:

答案 0 :(得分:2)

你的助手不应该有side effects。帮助者的工作是反应性地读取和/或转换数据,而不是改变状态。您应该使用帮助程序之外的setInterval随机选择一本新书。这是一个有效的解决方案:

var THREE_MINUTES = 3 * 60 * 1000;

var chooseRandomBook = function() {
  // fetch all of the published books
  var books = Books.find().fetch();

  // if there is only one book, just keep it and return
  if (books.length === 1)
    return Session.set('currentBookId', books[0]._id);

  // extract an array of book ids which don't contain the current book id
  var bookIds = _.chain(books)
    .pluck('_id')
    .without(Session.get('currentBookId'))
    .value();

  // choose a random id from the array
  var bookId = Random.choice(bookIds);

  // set the currentBookId to our random choice
  Session.set('currentBookId', bookId);
};

Template.book.helpers({
  book: function() {
    return Books.findOne(Session.get('currentBookId'));
  }
});

Template.book.created = function() {
  // choose a random book every three minutes, store the handle for cleanup
  this.handle = Meteor.setInterval(chooseRandomBook, THREE_MINUTES);
};

Template.book.destroyed = function() {
  // stop choosing books when we are done with this template
  Meteor.clearInterval(this.handle);
};