2013-12-12 3 views
1

백본을 조금 더 사용하려고 시도 중입니다. 과거에 백본보기 만 사용한 사람에게서 모델 및 컬렉션을 사용하고 있습니다.백본 모델 방법이 증가하지 않음

지금 바로 의견을 게시 할 때 댓글 수를 늘리려고합니다.

모델 :

Comment = Backbone.Model.extend({ 
    defaults: { 
     text: null, 
     count: 0 
    }, 

    updateCount : function() { 
     console.log(this.set('count', this.get('count') + 1)); 
     console.log(this.get('count')); 
    } 
}); 

컬렉션 :

CommentsCollection = Backbone.Collection.extend({ 
    model: Comment, 
    initialize: function (models, options) { 
     this.on("add", options.view.appendComment); 
     this.on('add', options.view.resetComment); 
    } 
}); 

보기 :

CommentsView = Backbone.View.extend({ 
     el: $("body"), 
     initialize: function() { 
      _.bindAll(this, 
        'addComment', 
        'appendComment', 
        'resetComment' 
        ); 
      this.comments = new CommentsCollection(null, { 
       model: Comment, 
       view: this 
      }); 
     }, 
     events: { 
      "click #post-comment": "addComment" 
     }, 

     addComment: function (evt) { 
      var $target = $(evt.currentTarget); 
      var $container = $target.closest('#comment-wrapper'); 
      var text = $container.find('textarea').val(); 

      var comment = new Comment({ 
       text: text 
      }); 

      //Add a new comment model to our comment collection 
      this.comments.add(comment); 

      return this; 
     }, 

     appendComment: function (model) { 
      $('#comments').prepend('<div> ' + model.get('text') + '</div>'); 
      model.updateCount(); 

      return this; 
     }, 

     resetComment: function() { 
      $('textarea').val(''); 
     } 
    }); 

왜 항상 코멘트를 추가 한 다음 확인하기 위해 콘솔을 표시 게시를 클릭합니다 (1을 반환)?

데모 : http://jsfiddle.net/ZkBWZ/

답변

0

당신이 Comment 모델 수를 저장하고 있기 때문에이 일어나고있다. 제출 버튼을 누를 때마다 count0으로 설정된 Comment이 새로 작성됩니다. 그런 다음 updateCount 메서드는 해당 새 모델의 개수를 업데이트하므로 항상 1이 표시됩니다.

몇 개의 주석이 작성되었는지 확인하려면 방금 크기를 살펴 보시기 바랍니다. CommentsCollectionappendComment에서 다음과 같이 할 수 있습니다.

appendComment: function (model) { 
     $('#comments').prepend('<div> ' + model.get('text') + '</div>'); 
     // Get the number of comments 
     console.log(model.collection.models.length); 

     return this; 
    },