简体   繁体   中英

backbone.js this.el not fetched/selected on dynamically loaded views

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!

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM