2016-07-05 89 views
0

這裏呈現的觀點是我的html:無法使用骨幹

<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Document Router</title> 
    <script src="jquery-1.7.2.js"></script> 
    <script src="underscore.js"></script> 
    <script src="backbone.js"></script> 
    </head> 
    <body> 
    <script type="text/javascript"> 
     var documents = [ 
     new Backbone.Model({ 
      title: 'JavaScript Modules', 
      content: 'why do we need modules? Organising JavaScript into modules makes it easier to reason about programs and makes it possible to test.' 
     }), 
     new Backbone.Model({ 
      title: 'Module Systems', 
      content: 'There are three competing module systems at the moment: CommonJS, AMD and ECMAscript Harmony modules' 
     }) 
     ]; 

     var DocumentView = Backbone.View.extend({ 
     render: function() { 
      this.$el.append(this.make('h1', null, this.model.get('title'))); 
      this.$el.append(this.make('div', null, this.model.get('content'))); 
      return this; 
     } 
     }); 
    </script> 
    </body> 
</html> 

而且在控制檯我已經試過這樣的事情:

var dv= new DocumentView(); 
undefined 
dv.render(); 

,並得到了錯誤,如

env.html:51 Uncaught TypeError: Cannot read property 'get' of undefined(…)render @ env.html:51(anonymous function) @ VM359:1

可能是什麼問題,爲什麼我不能渲染

回答

0

您在render方法中使用this.model.get,但您的視圖沒有定義模型,因此錯誤。你應該通過在模型實例,同時創造像

new DocumentView({model: document.models[0]}) 

視圖實例或設置this.model = modelInstance某個視圖內才呈現的,如initialize方法爲你的代碼工作中。

此外,您還未在視圖中定義任何make方法,因此this.make也可能會引發錯誤。

0

創建它時將模型傳遞到視圖。

var dv = DocumentView({ 
    model: documents[0] //Passing the first model 
}); 

dv.render(); 

這裏是一個工作fiddle