Reputation: 2775
I am having a problem with dynamically loaded views not being able to attach to the this.el
scope variable.
To illustrate what I am trying to achieve:
HTML PAGE
<html>
<head> head stuff </head>
<body>
<div id="appWrap"></div>
</body>
</html>
Now if I had a view called View.PageSetUp that will add a couple of set up divs to #appWrap I get:
HTML PAGE - 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>
My problems come when I want to add a specific view to the content stage because this.el
will not see the dynamically loaded $('#content')
.
Trying to then reload the this.el in the initialize function turned out to be a BIG no no… it didn't like it.
this.el = $('#content'); // rubbish idea!
It feels like dynamically loaded templates and views must be viable in a javascript application, so how would I make this work?
I guess one possibility is that when I am loading my scripts the el is set up then and there:
App.Views.Channel = Backbone.View.extend({
………………
})
Should I be using a loader to make this work? If so, any recommendations? I have experience with required but would it be too much for something so simple?
Thanks for your help!
Upvotes: 1
Views: 1166
Reputation: 1475
You can set el
in the view itself, but do it with tagName, className and id. Something like this:
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;
Upvotes: 1
Reputation: 2775
I've worked out the solution to this, so I'll leave it here incase anyone else has the same problem.
Basically I was setting el
in the view itself:
App.Views.Channel = Backbone.View.extend({
el : $('#myID'),
………………
})
Where I should have set it when I called a new instance of the view.
newView = App.Views.Channel(model, { el: $("#search_container") });
All seems to work anyway!
Upvotes: 2