2016-10-06 38 views
0

我在Backbone.js中編寫了一個簡單的應用程序,並且我有一個佈局視圖來呈現其中的所有其他視圖。在我index.html文件我有以下幾點:在嘗試呈現佈局視圖時無法讀取未定義的屬性'呈現'

<section id="layout"> 
    <section id="outlet"></section> 
</section> 

在我layout.js我有這樣的:

var LayoutView = Backbone.View.extend({ 
    el: '#layout', 
    render: function (view) { 
     if (this.child) this.child.remove(); 
     this($('#outlet').html((this.child = view).render().el); 
     return this; 
    } 
}); 

在我router.js我有以下代碼:

var AppRouter = Backbone.Router.extend({ 
    routes: { 
     '': 'home' 
    }, 
    initialize: function (options) { 
     this.layout = options.layout; 
    }, 
    home: function() { 
     // renders a collection view 
     this.layout.render(new ResumeList({collection: resumes})); 
    } 
}); 

最後在main.js我有這個:

$(document).ready(function() { 
    var layout = new LayoutView().render(); 
    var router = new AppRouter({layout: layout}); 
    Backbone.history.start(); 
}); 

但每次我試圖某處導航或剛開始的默認頁面控制檯返回我下面的錯誤時間:

jQuery.Deferred exception: Cannot read property 'render' of undefined TypeError: Cannot read property 'render' of undefined 
at n.render (http://localhost:8080/js/views/layout.js:5:51) 
at HTMLDocument.<anonymous> (http://localhost:8080/js/main.js:2:35) 
at j (http://localhost:8080/node_modules/jquery/dist/jquery.min.js:2:29948) 
at k (http://localhost:8080/node_modules/jquery/dist/jquery.min.js:2:30262) undefined 
jquery.min.js:2 Uncaught TypeError: Cannot read property 'render' of undefined 
+1

嘗試在'LayoutView'初始化中移除'render()'調用,即'var layout = new LayoutView()' –

回答

1

你LayoutView預計子視圖傳遞到它的渲染功能。

render: function (view) { 
    if (this.child) this.child.remove(); 
    this($('#outlet').html((this.child = view).render().el); 
    return this; 
} 

但是在您的main.js文件中,您正在調用不帶參數的render。

var layout = new LayoutView().render(); 

render()應該由你的AppRouter被調用,所以如果你只是將其更改爲:

$(document).ready(function() { 
    var layout = new LayoutView(); 
    var router = new AppRouter({layout: layout}); 
    Backbone.history.start(); 
}); 

應該從那裏工作。