Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
   });
like image 832
fe-ninja Avatar asked May 18 '13 19:05

fe-ninja


People also ask

What does render () do in react native?

React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

What does the render () This props do?

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

Can we write function in render?

A function in the render method will be created each render which is a slight performance hit. It's also messy if you put them in the render, which is a much bigger reason, you shouldn't have to scroll through code in render to see the html output. Always put them on the class instead.


1 Answers

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);
}
like image 74
Gurpreet Singh Avatar answered Oct 04 '22 20:10

Gurpreet Singh