javascript - 未捕获的类型错误 : Cannot call method 'on' of undefined - Backbone. js

标签 javascript jquery backbone.js

我的应用程序出现错误,不知道为什么。

Uncaught TypeError: Cannot call method 'on' of undefined 

它发生在我的 Collection View 上,遵循代码:

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

最佳答案

 this.workoutsView = new App.WorkoutsView();

应该传入一个集合

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

因为当您在 View 的 Initialize 方法中将事件绑定(bind)到它时,您的 View 在初始化时期望有一个可用的集合。

关于javascript - 未捕获的类型错误 : Cannot call method 'on' of undefined - Backbone. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860749/

相关文章:

JavaScript - 如果表单上的文本字段中的默认值发生更改,则强制重定向

javascript - 打印功能重置其他 jQuery 事件

jquery - 使用jquery计算图像数量,然后输出#

asp.net - jQuery黑莓ajax问题

jquery - 表行在调用 JQuery Remove 后仍然占用空间

javascript - Backbone /rails 之间使用 REST url 进行通信时出现问题

javascript - 在 Backbone 中添加了多个模态

javascript - ReactJS .default 不是构造函数

php - Bootstrap : Accordion within accordion, 显示动态内容

javascript - 下划线标记在 backbone 中有什么作用,我们什么时候使用它?