【问题标题】:Backbone model method not incrementing骨干模型方法不递增
【发布时间】:2013-12-30 07:48:25
【问题描述】:

我正在尝试更多地了解 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/

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    发生这种情况是因为您将计数存储在 Comment 模型上。每次点击提交按钮时,都会创建一个新的Comment,其中count 设置为默认值0。方法 updateCount 然后更新该全新模型的计数,因此您始终看到 1。

    如果您只是想确定制作了多少 cmets,我建议您只查看 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;
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 2018-09-06
      • 2014-06-25
      • 2012-05-04
      • 2012-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多