2013-12-12 56 views
1

我正在试图挖掘Backbone多一点,并且从过去只使用Backbone视图的人中,我现在正在尝试使用模型和集合。骨干模型方法不增加

现在,当我发表评论时,我尝试增加评论数量。

型号:

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模型计数。每次点击提交按钮时,都会创建一个新的Comment,其中count设置为默认值0。方法updateCount然后更新该全新模型的计数,所以你总是看到1.

如果你只是想确定已经做了多少评论,我建议你看看大小的CommentsCollection。在appendComment,你可以这样做:

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

     return this; 
    },