1

这是我的骨干:

App.Models.Count = Backbone.Model.extend({
        url: this.url,
        initialize: function() {
            this.fetch({
                success: function(data, response) {
                    this.count = data.get('count');
                    console.log(this.count);  // 9, correct answer
                }
            });
        }
    });

    App.Views.Count = Backbone.View.extend({
        tagName: 'span',
        initialize: function(options) {
            this.count = this.options.count;
            console.log(options);  // returns correctly
            this.model.on('reset', this.render, this);
        },
        render: function() {
            console.log('test'); // not called
            this.$el.html(this.model.toJSON());
            return this;
        }
    });

在我的路线中:

var mc = new (App.Models.Count.extend({'url' : 'main-contact-count'}))();
var mcv = new (App.Views.Count.extend({ model: mc }))();
console.log(mcv); // 9, correct answer
$('#contactCount').html(mcv);

如您所见,我的render方法永远不会被调用。此外,根据我在 Firebug 中看到的 console.log 内容,我的视图似乎在我的模型之前被调用。是因为异步吗?为什么不render叫?

4

1 回答 1

2

您正在以一种时髦的方式使用 Backbone。这是执行此操作的更标准方法:

App.Models.Count = Backbone.Model.extend({
    urlRoot: "main-contact-count"
});

App.Views.Count = Backbone.View.extend({
    tagName: 'span',
    initialize: function(options) {
        this.model.on('change', this.render, this);
    },
    render: function() {
        console.log('test');
        this.$el.html(this.model.toJSON());
        return this;
    }
});

在路由器中:

var mc = new App.Models.Count();
var mcv = new App.Views.Count({model: mc});
mc.fetch();
$('#contactCount').html(mcv.el);

编辑

事实证明,您正在收听 Backbone 模型上的“重置”。这永远不会发生。尝试听“改变”而不是重置:

this.model.on('change', this.render, this);
于 2013-01-10T16:08:15.367 回答