2013-05-31 57 views
8

我的应用程序出现了一些错误,不知道为什么。Uncaught TypeError:无法调用未定义的方法'''' - Backbone.js

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

'this.collection'究竟是什么? –

+1

你可以显示你用来实例化视图的代码吗? –

+0

@MarkLinus锻炼集合,我将添加代码 –

回答

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

应该在传递收藏

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

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

+1

它的作品@sushanth!非常感谢你! –

+1

欢迎您:) –

相关问题