简体   繁体   中英

Uncaught TypeError: Cannot call method 'on' of undefined - Backbone.js

I'm having some error in my app and don't know why.

Uncaught TypeError: Cannot call method 'on' of undefined 

It happens on my collection view, follow the code:

App.WorkoutsView = Backbone.View.extend({
    initialize: function(){
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.addAll, this);
    },

    render: function() {
        this.addAll();
        return this;
    },

    addAll: function() {
        this.$el.empty();
        this.collection.forEach(this.addOne, this);
    },

    addOne: function(Workout) {
        var workoutView = new App.WorkoutView({model: App.Workout});
        this.$el.append(workoutView.render().el);
    }
});

the problem is on:

this.collection.on('add', this.addOne, this);

Anyone knows why?

** Edit: Collection code **

App.WorkoutItems = Backbone.Collection.extend({
    model: App.Workout,
    url: '/workouts',

    localStorage: function() {new Backbone.LocalStorage('Workout')},

    initialize: function() {
        this.on('remove', this.hideWorkout, this);
    },

    hideWorkout: function() {
        model.trigger('hide');
    },

    focusOnWorkoutItem: function() {
        var modelsToRemove = this.filter(function(workoutItem) {
            return workoutItem.id != id;
        });
    this.remove(modelsToRemove);
    }
});

Edit: my Router code where i'm instantiating WorkoutsView:

App.Router = Backbone.Router.extend({
    routes: {
        '':'index'
    },

    initialize: function() {
        this.workoutItems = new App.WorkoutItems();
        this.workoutsView = new App.WorkoutsView();
        this.workoutsView.render();
    },

    index: function() {
        $('#workouts').html(this.workoutsView.el);
        this.workoutsItem.fetch();
    }
});

new App.Router;
Backbone.history.start();
 this.workoutsView = new App.WorkoutsView();

is supposed to pass in a collection

 this.workoutsView = new App.WorkoutsView({collection : this.workoutItems});

Because you view when being initialized is expecting to have a collection available to it as you are binding a event to it in the Initialize method of the view.

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