8

我的应用程序有一些错误,不知道为什么。

Uncaught TypeError: Cannot call method 'on' of undefined 

它发生在我的收藏视图中,请按照以下代码:

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);
    }
});

问题出在:

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

有谁知道为什么?

** 编辑:收藏代码 **

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);
    }
});

编辑:我在其中实例化 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();
4

1 回答 1

6
 this.workoutsView = new App.WorkoutsView();

应该传入一个集合

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

因为您在初始化时查看期望有一个可用的集合,因为您在视图的 Initialize 方法中将事件绑定到它。

于 2013-05-31T15:36:54.110 回答