Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between: $(this.el).html and this.$el.html

What's the difference between:

$(this.el).html 

and

this.$el.html 

Reading a few backbone examples and some do it one way and other another way.

like image 809
CLiown Avatar asked Jul 16 '12 20:07

CLiown


People also ask

What is El in HTML?

el is just an identifier and it refers to an element, a DOM element, which is a convention in that library.

What is $() Javascript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document.

What is $El in backbone?

It is so late to answer it but --> this.$el is a reference to the element in the context of jQuery, typically for use with things like .html() or .addClass() , etc. For example, if you had a div with id someDiv, and you set it to the el property of the Backbone view, the following statements are identical: this.$


1 Answers

$(this.el) wraps an element with jQuery (or Zepto). So, if your view HTML was this:

<div id="myViewElement"></div>

...and this.el referenced that div, then $(this.el) would be the equivalent of retrieving it directly via jQuery: $('#myViewElement').

this.$el is a cached reference to the jQuery (or Zepto) object, so a copy of what you would get from calling $(this.el). The intent is to save you the need to call $(this.el), which may have some overhead and therefor performance concerns.

Please note: the two are NOT equivalent. this.el alone is a reference to a host object HTMLElement -- no libraries involved. This is the return of document.getElementById. $(this.el) creates a new instance of the jQuery/Zepto object. this.$el references a single instance of the former object. It is not "wrong" to use any of them, as long as you understand the costs of multiple calls to $(this.el).

In code:

this.ele = document.getElementById('myViewElement'); this.$ele = $('#myViewElement');  $('#myViewElement') == $(this.ele); 

Also, it is worth mentioning that jQuery and Zepto have partial internal caches, so extra calls to $(this.el) might end up returning a cached result anyway, and that's why I say "may have performance concerns". It also may not.

Documentation

  • view.$el - http://backbonejs.org/#View-$el
  • $ in backbone - http://backbonejs.org/#View-dollar
  • jQuery base object - http://api.jquery.com/jQuery/
  • Zepto base object - http://zeptojs.com/#$()
like image 159
Chris Baker Avatar answered Oct 02 '22 19:10

Chris Baker