简体   繁体   中英

Why this render function doesn't work?

I have been playing with backbone and trying to learn it. I'm stuck at this point for a while. Not able to figure out what's wrong with following code?

  render: function() {
    this.$el.empty();
    // render each subview, appending to our root element
    _.each(this._views, function(sub_view) {
      this.$el.append(sub_view.render().el); // Error on this line
   });

You have got context issue. this you are refering to doesn't contain the $el you are looking for. You can fix this by declaring a self variable that points to appropriate this . Following code should work for you.

render: function() {
    var self = this; //Added this line to declare variable (self) that point to 'this' 
    this.$el.empty();
    _.each(this._views, function(sub_view) {
      self.$el.append(sub_view.render().el); //Used 'self' here instead 'this' 
});

Side Note: As you are leaning backbone also you should know about a very commong JavaScript problem with document reflow. You are render a view for every single model in the collection. It can lead to performance issues and especially on old computers and mobile devices. You can optimise your code by rendering everything in container and appending it once, rather than updating DOM each time. Here is an example:

render: function() {
  this.$el.empty();
  var container = document.createDocumentFragment();
  _.each(this._views, function(sub_view) {
    container.appendChild(sub_view.render().el)
  });
  this.$el.append(container);
}

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