骨干模型方法不递增

时间:2013-12-12 03:14:48

标签: javascript backbone.js

我正在尝试更多地使用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(添加注释并单击Post然后查看控制台以查看)?

演示:http://jsfiddle.net/ZkBWZ/

1 个答案:

答案 0 :(得分: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;
    },
相关问题