gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:14:57 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com