如何将.show()更改为.thoggle()而不复制函数中的项(如何重构)

How to change .show() to a .toggle() without duplicating items in my function(how can I refactor)

本文关键字:函数 何重构 复制 重构 thoggle show      更新时间:2023-10-24

我目前正在使用我的第一个backbone.js应用程序。我做了一个"showcomment"函数,它在underscore.js模板中呈现一个视图,并将其呈现到我的视图中。问题是,我想在点击按钮时"切换"所有评论,而不仅仅是"显示"评论视图。如何重构这个"showComment"函数以不复制当前视图?success回调迭代注释视图中的每个注释,然后渲染它。使用toggle,我希望它在每次单击toggle时只渲染一个视图,而不是渲染同一个视图多次。

示例:

用户单击显示评论按钮,将显示5条评论。

用户点击显示评论按钮,评论被隐藏。

用户单击显示评论按钮,将显示10条评论(前5条,由于成功功能呈现了一个全新的视图,最初显示的前5个问题将附加到前5个,因此现在总共有10条)。

这是的主要功能

 showComments: function() {
      this.commentsView = this.$el.find(".comments_container");
      this.commentsView.show(); ***INSTEAD OF .show() I CAN USE .TOGGLE() but I get DUPLICATES WHENEVER THE VIEW IS RENDERED ***
      this.commentCollection = new app.CommentList();
      // // debugger;
      var self = this;
      this.commentCollection.fetch({
        data: { question_id: this.$el.attr('question_id') },
        success: function(collection) {
          collection.each(function(comment) {
            var commentView = new app.CommentView({model: comment});
            var html = commentView.render().el;
            self.commentsView.append(html);
          });
        }
      });

这是主干事件:

'click .show_comments': 'showComments'

任何建议都将不胜感激,谢谢!

有几种方法可以做到这一点。

您可以在页面加载时呈现和隐藏注释视图,然后绑定按钮commentsView.toggle.

或者,在showComments函数中,您可以进行评估,检查commentsView是否已经创建。

If (this.commentView != null)
  //toggle
else
  //create your view and show it