模型更改时,主干视图不会刷新

时间:2013-01-21 23:56:50

标签: backbone.js backbone-views

我收到错误'对象[对象]在控制台中没有方法'apply''。请看小提琴.. http://jsfiddle.net/vineet85/AQx63/6/

var RefreshingView = new Backbone.View.extend({
    initialize: function() {
        this.model.on('change', this.render, this);
    },
    render: function() {
        this.$el.html(this.model.get('text'));
    }
});

var m = new Backbone.Model({text: new Date().toString()});
var myView = new RefreshingView({model: m, el: 'body'});

myView.render();

setInterVal(function() {
    m.set({text: new Date().toString()});
}, 1000);

1 个答案:

答案 0 :(得分:2)

您的语法有点偏差,首先“声明”您的观点和模型应该省略新关键字,其次您不应该尝试“实例化” backbone.js模型,直接尝试以下

    var RefreshingView = Backbone.View.extend({
        el: 'body',

        initialize: function () {
            this.model.on('change', this.render, this);
        },
        render: function () {
            this.$el.html(this.model.get('text'));
        }
    });

    var MyModel = Backbone.Model.extend({
        text: null
    });

    var m = new MyModel({ text: new Date().toString() });
    var myView = new RefreshingView({ model: m, el: 'body' });

myView.render();

setInterval(function () {
    m.set({ text: new Date().toString() });
}, 1000);

Updated jsFiddle