简体   繁体   中英

“Cannot call method 'on' of undefined” issue

How to solve it?

View:

App.Views.ModelsIndex = Backbone.View.extend({
    tagName: 'div',
    initialize: function() {
        this.template = _.template($('#container').html());

        // Cannot call method 'on' of undefined
        this.model.on('change', this.render, this);
    },
    render: function() {
        $(this.el).html(this.template({'model' : this.model}));
        return this;
    }
});

Router:

App.Routers.Models = Backbone.Router.extend({
    routes: {
        '': 'index',
        'admin/:id' : 'show'
    },
    initialize: function() {
        this.collection = new App.Collections.Models();
        this.collection.fetch();
    },
    index: function() {
        view = new App.Views.ModelsIndex({'collection' : this.collection});
        $('#container').html(view.render().el);
    },
    show: function(id) {
        alert('entry id:' + id);
    }
});

Collection:

App.Collections.Models = Backbone.Collection.extend({
    url: "/app_dev.php/partner/api/users/1"
    , model: App.Models.Model
});

Your router passes a collection to your view constructor

new App.Views.ModelsIndex({'collection' : this.collection});

but you use a model in your view :

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

Pick one and stick with it :

App.Views.ModelsIndex = Backbone.View.extend({
    initialize: function() {
        this.template = _.template($('#container').html());
        this.collection.on('change', this.render, this);
    }
    ...
});

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