【问题标题】:MeteorJS + Iron-Router: How can I call the next item in the collection using pathFor?MeteorJS + Iron-Router:如何使用 pathFor 调用集合中的下一个项目?
【发布时间】:2014-08-28 14:49:28
【问题描述】:

在发布这个问题之前我做了很多研究,但找不到答案。我确信这是一项简单的任务,但由于某种原因,它让我无法接受。

我有一个“帖子”类型的页面,其中列出了我收藏中的所有项目,还有一个“单个帖子”页面来显示所选帖子的内容。我有两个分页箭头用于转到上一项和下一项。如何获取上一篇/下一篇文章的 URL 并将其显示在我的模板中?

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    我创建了完全满足您需要的示例应用程序。 请检查:https://github.com/parhelium/meteor-so-post-next-prev/tree/master

    此代码重要部分的简要说明(请参阅repo 了解更多详细信息):

    服务器端

    首先你需要有一些模型:

     {title:"1 post", createdAt:moment("01-10-1995", "DD-MM-YYYY").toDate()}
    

    和发布功能:

    Meteor.publish("postDetailsNext",function(postId){ });
    Meteor.publish("postDetailsPrev",function(postId){ });
    Meteor.publish("postDetails",function(postId){});
    

    “棘手”的部分是如何编写查询以获取 nextprev 帖子。

    Meteor.publish("postDetailsNext",function(postId){
    
          // load post object which should be displayed in 'postDetails' route
          var post = Posts.findOne({_id:postId});
    
          // find one post from sorted cursor which is older than main post 
          return Posts.find({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}, limit:1})
    });
    

    和类似的:

    Meteor.publish("postDetailsPrev",function(postId){  
          var post = Posts.findOne({_id:postId});
          return  Posts.find({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}, limit:1})
      });
    

    请注意,来自上述发布函数的查询在 sort field 中有所不同。

    客户端

    this.route('postDetails',{
          where:'client',
          path:'/post/:_postId',
          template:'postDetails',
          waitOn:function(){
            return [
                Meteor.subscribe('postDetails', this.params._postId),
                Meteor.subscribe('postDetailsPrev', this.params._postId),
                Meteor.subscribe('postDetailsNext', this.params._postId)
            ]
          },
          data:function(){
            var post = Posts.findOne({_id:this.params._postId});
            if(post == null) return {};
            else
                return {
                    post : Posts.findOne({_id:post._id}, {limit:1}),
                    prev : Posts.findOne({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}}),
                    next : Posts.findOne({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}})
                }
            }
          }
        })
    

    【讨论】:

      【解决方案2】:

      你可以在不使用铁路由器路径的情况下做到这一点

      通过使用这个包https://github.com/alethes/meteor-pages 它提供了一个不同的选项来使用分页

      您也可能有兴趣查看此网址 Best pattern for pagination for Meteor http://www.youtube.com/watch?v=WSwe_weshQw

      【讨论】:

      • 欢迎来到 Stack Overflow!您应该始终尝试在答案中发布代码。如果链接断开,您的答案将失去价值。
      猜你喜欢
      • 2014-12-15
      • 1970-01-01
      • 2016-03-25
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      相关资源
      最近更新 更多