Smith
Smith

Reputation: 1490

what is difference between $ and this.$ in backbone

what is difference between $ and this.$ in backbone Js
This is in reference to the example of book
Addy Yosmani Book Example

Upvotes: 1

Views: 222

Answers (2)

dthree
dthree

Reputation: 20730

$ is jQuery, and refers to a jQuery selector.

When one uses this.$, it narrows the jquery selection to any DOM element that is a child of the Backbone.View.

Examples:

// selects the overall DOM body of your page.
$(body).append(something);

// This will not work.
this.$(body); // -> returns nothing.

var View = Backbone.View.extend({

  render: function() {

    // refers to the root element of this Backbone View.
    this.$el.append(something); 
  }

});

More data

this.$el is a special property Backbone applies to the view, which refers to your root element (in your case, <p>).

If <p> has a child named

<div class='pinkElephant'></div>

you can safely say

this.$('pinkElephant')

to refer to the pink elephant in that view, without worrying about selecting the 5 other pink elephants in the other 5 instances of your same Backbone View.

CSS Selector basics:

When using jQuery (and any CSS selector), to select elements by class name, you do:

$('.whatever');

By id, you do:

$('#whatever');

If three different elements have the class name whatever, jQuery will then be referring to all three elements.

Upvotes: 1

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

$ is jQuery. this.$ rather someView.$ is a function in a View which performs selection on DOM elements which are children of el of a View.

For example view.$('.someClass') (check this) is equivalent to view.$el.find('.someClass') where $el (check this) is a cached jQuery object for the view's element.

Ideally, inside a view you should operate on a part of DOM which descendant of view's el. So, view.$ is the perfect solution in this case.

Upvotes: 3

Related Questions