2013-05-31 54 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

歡迎您:) –

相關問題