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(添加注释,然后点击发布,然后查看控制台看)?