[英]backbone.js this.el not fetched/selected on dynamically loaded views
我遇到了動態加載的視圖無法附加到this.el
scope 變量的問題。
為了說明我想要實現的目標:
HTML 頁
<html>
<head> head stuff </head>
<body>
<div id="appWrap"></div>
</body>
</html>
現在,如果我有一個名為 View.PageSetUp 的視圖,它將向 #appWrap 添加幾個設置 div,我得到:
HTML 頁面 - View.AppSetUp
<html>
<head> head stuff </head>
<body>
<div id="appWrap">
<div id="nav">buttons…</div>
<div id="side">side stuff…</div>
<div id="content"></div>
</div>
</body>
</html>
當我想將特定視圖添加到內容階段時,我的問題就出現了,因為this.el
不會看到動態加載的$('#content')
。
然后嘗試在初始化 function 中重新加載 this.el 原來是一個很大的不不......它不喜歡它。
this.el = $('#content'); // rubbish idea!
感覺動態加載的模板和視圖在 javascript 應用程序中必須是可行的,那么我將如何使其工作?
我想一種可能性是,當我加載我的腳本時,el 會在那里設置:
App.Views.Channel = Backbone.View.extend({
………………
})
我應該使用裝載機來完成這項工作嗎? 如果是這樣,有什么建議嗎? 我有必要的經驗,但是對於這么簡單的事情來說會不會太多?
謝謝你的幫助!
我已經解決了這個問題,所以我會把它留在這里,以防其他人有同樣的問題。
基本上我是在視圖本身中設置el
:
App.Views.Channel = Backbone.View.extend({
el : $('#myID'),
………………
})
當我調用視圖的新實例時,我應該在哪里設置它。
newView = App.Views.Channel(model, { el: $("#search_container") });
無論如何,一切似乎都有效!
您可以在視圖本身中設置el
,但使用 tagName、className 和 id 進行設置。 像這樣的東西:
App.Nav.View = Backbone.View.extend({
tagName: "div",
id: "nav",
render: function() {
/* Nav buttons */
}
});
App.View = Backbone.View.extend({
el: $("#appWrap"),
initialize: function() {
var appNavView = new App.Nav.View;
$(this.el).append(appNavView.render().el);
}
});
appView = new App.View;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.