Cómo cambiar .show() a .toggle() sin duplicar elementos en mi función (cómo puedo refactorizar)

I am currently working in my first backbone.js app. I made a "show comment" function that renders a view in an underscore.js template and renders it to my view. The problem is, I want to "toggle" all the comments when a button is clicked, not just "show" commentView. How can I refactor this "showComment" function to not duplicate the current view? The success callback iterates over each comment in the comment view and then renders it. Using toggle, I would like it to just render 1 view, not render the same view, multiple times on each click when clicking toggle.


User clicks the show comments button, 5 comments are displayed.

User clicks the show comments button, comments are hidden.

User clicks the show comments button, 10 comments are displayed (the first 5 and since the success function renders a whole new view, the first 5 questions initially displayed are appended to the first 5, so there are 10 total now).

Aquí está la función principal

 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;
        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;

Here is the backbone Event:

'click .show_comments': 'showComments'

Cualquier sugerencia será apreciada, ¡gracias!

preguntado el 27 de noviembre de 13 a las 05:11

1 Respuestas

There is a few ways that you could do it.

You could render and hide the comment view on page load and then bind the button commentsView.toggle.

OR in your showComments function you can have an evaluation that checks to see if the commentsView is already created.

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

respondido 27 nov., 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.