-2

What does this refer to in initialize and render properties?

JavaScript code:

SearchView = Backbone.View.extend({ 
  initialize: function(){
    this.render(); 
  },
  render: function(){
    // Compile the template using underscore
    var template = _.template( $("#search_template").html(), {} );
    // Load the compiled HTML into the Backbone "el"
    this.$el.html( template ); 
  }
});
var search_view = new SearchView({ el: $("#search_container") });

HTML code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Backbone.js App</title>
  <meta name="description" content="">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
</head>
<body>
<div id="search_container"></div>

<script type="text/template" id="search_template">
  <label>Search</label>
  <input type="text" id="search_input" />
  <input type="button" id="search_button" value="Search" />
</script>

<script src="app.js"></script>
</body>
</html>
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Ivan
  • 361
  • 1
  • 3
  • 11
  • this refers to the instance created by the constructor function `new SearchView` – Abhinav Galodha Dec 19 '16 at 19:42
  • This is based on [_What is a view?_](https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-view) tutorial. – Emile Bergeron Dec 19 '16 at 19:48
  • 1
    Easiest way to find out is to `console.log(this)` and see what is outputted on the console – Patrick Evans Dec 19 '16 at 19:48
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Emile Bergeron Dec 19 '16 at 19:58
  • Similar and recent question: [What is `this` inside a Backbone model?](http://stackoverflow.com/q/40902062/1218980) but the answer is not in depth about the context. – Emile Bergeron Dec 19 '16 at 20:05

1 Answers1

0

In your specific case, it's search_view.

Try the following:

  • add a console.log('this in initialize', this) into your initialize method
  • add a console.log('this in render', this) into your render method
  • add a console.log('search_view', search_view) after var search_view = new SearchView(...);

and see how those results are the same/different.

therobinkim
  • 2,500
  • 14
  • 20