简体   繁体   中英

Backbone View does not recognize the model

Model

var MyModel = Backbone.Model.extend({
        url:'http://localhost:3000/getMiningInfo',
        defaults: {
           blocks: "",
        },
        parse: function(resp) {
           return resp;
        }
});
var info = new MyModel();
info.fetch();

View

var MyInfoView = Backbone.View.extend({
    tagName:'table',
    id:'info',
    class:'table table-hover',
    template:_.template('<tbody><tr><td><span>Number Of Blocks</span></td>'+
                   '<td><span><%= blocks %> </span></td>'+
                '</tr></tbody>'),
    initialize: function() {
                   this.model.on('change', this.render, this);
    },
    render: function() {
           var attributes = this.model.toJSON();
           this.$el.html(this.template(attributes));
    } 
});
var myView = new MyInfoView({model: info});
myView.render();
$('#info').html(myView.el);

I get error for this.model.on and this.model.toJSON() as Uncaught TypeError: Object #<HTMLDivElement> has no method 'on' or no method 'toJSON' respectively.

I think you want the view to listen for changes on the model.

initialize: function() {

   this.listenTo( this.model, 'change', this.render ); 

}

Backbone recommends using 'listenTo' over 'on' for garbage cleaning purposes anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM