为什么我在主干道上来回跳跃

Why am I bouncing between routes in backbone?

本文关键字:跳跃 主干道 为什么      更新时间:2023-09-26

所以我有一个路由文件:

Nightbird.Routers.Posts = Nightbird.Routers.Core.extend({
  DEFAULT_TIMEOUT: 15000,
  fetchPostsTimeout: null,
  routes: {
    'posts': 'posts',
    'post/:id': 'post',
  },
  posts: function() {
    var postsCollection = new Nightbird.Collections.Posts();
    postsCollection.fetch().then(this.postsRecieved, this.serverError);
    var self = this;
    this.fetchPostsTimeout = setInterval(function() {
      postsCollection.fetch().then(self.postsRecieved, self.serverError);
    }, this.DEFAULT_TIMEOUT);
  },
  post: function(id) {
    var postsCollection = new Nightbird.Collections.Posts({id: id});
    postsCollection.fetch().then(this.postRecieved.bind(this), self.serverError);
  },
  postsRecieved: function(collection, response, options) {
    var managementPostsView = new Nightbird.Views.ManagementPosts();
    managementPostsView.render(collection, this.currentPage);
  },
  postRecieved: function(collection, response, options) {
    new Nightbird.Views.ManagementPost(collection);
  },
})

我们在这里所做的就是定义当你访问上述路线时会发生什么。因此,如果你访问#posts路线,你会得到一个帖子列表,我们每15秒就会检查一次新帖子。

但假设你进入#posts,然后点击一篇帖子,然后进入#post/x,其中x是帖子id。让我们看看单个帖子的视图。

Nightbird.Views.ManagementPost = Nightbird.Views.Core.extend({
  comments: {},
  post: {},
  commentsTimeOut: null,
  errorMessage: '',
  initialize: function(postsObject) {
    this.post = postsObject;
    var postId = this.post.post.id
    var commentsCollection = new Nightbird.Collections.Comments(postId);
    commentsCollection.fetch().then(this.getComments.bind(this), this.errorMessage.bind(this));
    var self = this;
    this.commentsTimeOut = setInterval(function() {
      commentsCollection.fetch().then(self.getComments.bind(self), self.errorMessage.bind(self));
    }, 15000);
  },
  getComments: function(collection, response, options) {
    this.comments = collection;
    this.render()
  },
  errorMessage: function() {
    this.errorMessage = 'We could not retrieve comments for the post. We will try again in 15 seconds.';
  },

  render: function(collection) {
    React.renderComponent(new ManagementPost({
      post: this.post,
      comments: this.comments,
      errorMessage: this.errorMessage
    }), this.getBlogManagementElement()[0])
  }
});

很简单,我们得到这篇文章的评论,然后呈现这篇文章。请注意,在这里,我们每15秒检查一次新的评论并显示它们。我们用react来渲染成品。

那么问题出在哪里呢?

如果你在#posts上点击一个博客标题,然后被带到#posts/x,你会看到一篇有评论的帖子,太棒了。但15秒后,我们会闪回到帖子列表,然后15秒后返回到带有评论的帖子。它每15秒做一次。它不会在"中间"停止这样做,直到你刷新单个帖子页面上的页面,只有这样它才会停止来回闪烁。

是什么原因造成的?这是因为当你通过路由器在主干网中旅行时,它们不是真正的重定向吗?我应该使用主干Backbone.history.navigate('', {trigger:true})吗?如果是,我该如何传递ID之类的东西?或其他变量?

我正在尝试建立一个"实时"博客管理系统,这个闪烁的问题让我感到困惑。

setInterval返回一个值。当你想停止它时,你需要保留这个值并将其传递给clearInterval。Backbone没有办法自动为你做到这一点。