What is the difference between $ el and el in Backbone.js images?

Can you tell the difference between $el and el in Backbone.js images?

+54
javascript backbone-views
May 20 '13 at 9:34
source share
3 answers

lets say you do it

 var myel = this.el; // here what you have is the html element, //you will be able to access(read/modify) the html //properties of this element, 

with this

 var my$el = this.$el; // you will have the element but //with all of the functions that jQuery provides like, //hide,show etc, its the equivalent of $('#myel').show(); //$('#myel').hide(); so this.$el keeps a reference to your //element so you don't need to traverse the DOM to find the // element every time you use it. with the performance benefits //that this implies. 

one is the html element and the other is the jQuery element of the element.

+76
May 20 '13 at 16:07
source share

mu is too short in accuracy:

 this.$el = $(this.el); 

And it's easy to see why, look at the view _setElement function :

 _setElement: function(el) { this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); this.el = this.$el[0]; }, 

This ensures that el always a DOM element and that $el always a jQuery object. So, the following is true, although I used the jQuery object as a parameter or property of el :

 var myView = new Backbone.View({ el: $('.selector') }); // or var MyView = Backbone.View.extend({ el: $('.selector') }); 

What is a cached jQuery object?

This is a jQuery object contained within a variable for reuse. This avoids the costly operation of finding an element with something like $(selector) every time.

Here is an example:

 render: function() { this.$el.html(this.template(/* ...snip... */)); // this is caching a jQuery object this.$myCachedObject = this.$('.selector'); }, onExampleEvent: function(e) { // avoids $('.selector') here and on any sub-sequent example events. this.$myCachedObject.toggleClass('example'); } 

See the extended answer I wrote to find out more.

+2
Oct 29 '16 at 18:14
source share

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

 this.$el.html() $("#someDiv").html() $(this.el).html() 

this.el is a native DOM element not affected by jQuery.

0
Jul 24 '16 at 11:20
source share



All Articles