Peter Carter
Peter Carter

Reputation: 2728

How does "this" function in this code Backbone sample?

How does the this property function in this Backbone.js code sample?

Since the use strict directive is not specified within the code and no object is passed to any of the functions, does the Backbone.js code default to the global app object or does it do something else?

I'm assuming that this.render() probably renders to the DOM element specified by the el property passed in via the underscore template, but what about this.$el.html?

<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>
<div id="search_container"> </div>
<script type="text/javascript">
  var 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") }); 
</script>

Upvotes: 0

Views: 96

Answers (1)

Yura
Yura

Reputation: 2721

In this code sample this is the pointer to the instance view of the SearchView.

You could create many instances of that view, and each of those would have this directed at itself.


Every view instance has two properties that point to the DOM element of that view instance. .el points to the DOM element, and .$el is a jQuery object that points to that DOM element.

The benefit of .$el is that you can call any jquery methods on that object.

So this.$el.html() means you're calling jQuery.html method on the DOM element of that view instance.

In your code, you've compiled the template of that view and passed it to $el.html(), which inserts the HTML of the template into the DOM element of that view.


As for this.render() in the initialize, it just calls that instance's render method at the moment when that instance gets initialized, that is where you see the new keyword. New instance is created, initialize method is called automatically, which calls this.render().

Instead of calling this.render() in initialize you could, for example, call search_view.render() directly after the last line of your script.

Upvotes: 2

Related Questions