主干模型方法未递增

Backbone model method not incrementing

本文关键字:方法 模型      更新时间:2023-09-26

我正在尝试对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/

之所以会发生这种情况,是因为您将计数存储在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;
    },