2013-08-03 37 views
1

我想學習Backbone.js。我試圖在視圖中定義模型更改事件,但獲取以下javascript錯誤: 未捕獲TypeError:無法調用未定義的方法'on'Backbone.js TypeError:無法調用未定義的方法'開'

如果我從視圖中取出初始值,它會顯示文字沒有錯誤。

我是否擁有Backbone應用程序的正確基本結構? 我在做什麼錯?

$(document).ready(function rdy() 
{ 
    var Person = Backbone.Model.extend({ 
     defaults: { 
      name: 'Alex', 
      age: 33, 
      } 
     }); 

    person = new Person(); 

    var ContentView = Backbone.View.extend({ 
     el: '#content', 
     initialize: function() { 
     this.model.on('change', this.render, this); //ERROR HERE <---------- 
     }, 
    render: function() { 
     this.$el.html("Aargh Hello " + person.get('name')); 
     return this; 
     } 
    }); 

    var NavigationRouter = Backbone.Router.extend({ 
    routes: { 
     "": "defaultRoute" 
      }, 
    initialize: function (options) { 
     this.view = new ContentView({});   
     return this; 
     }, 
    defaultRoute: function (actions) { 
     this.view.render(); 
     } 
    }); 
    var navigationRouter = new NavigationRouter; 
    Backbone.history.start(); 
}); 

回答

2

您需要將模型傳遞到視圖中。像:

// Pass in the person you made earlier. Alternatively, you could use 
// new Person() instead of creating the person separately 
this.view = new ContentView({ model: person }); 

然後渲染功能,也應使用this.model

你也可以把視圖中的檢查,但如果視圖是要依靠有是一個Person模型,你應該讓它失敗,所以你不要忘記。

+0

謝謝,你的建議工作正常,我改變了渲染功能。我試過了:this.view = new ContentView({model:new Person()});作爲替代方式來做到這一點。但是,這並沒有迴應改變事件。 –

相關問題