Reputation: 5280
I have seen this bunch of code in a tutorial:
var searchTerm = this.$('#searchTerm').val().trim();
I would like to understand the utility of the this.
in front of the selector, it's the first time i see that.
Upvotes: 1
Views: 190
Reputation: 2313
In a Backbone.View
, this.$
gives a scoped version of jQuery. It is in fact equivalent to using this.$el.find
which is in turn equivalent to using $(this.el).find
.
Anyhow, the reason it is a good idea to use it is that it will only access html elements from within the view's element/rendered template. Thus, you don't have to worry about the rest of the html page and you will always select the element you expect to.
Imagine that you have a view that spawns sub-views and that each of these have an editable field. If you don't use the scoped version of jQuery to get the right editable field, you will have to give a unique id
to each of these html elements to make sure you will select the right one when retrieving it's content. On the other hand, if you use the scoped version, you will just have to give this editable field a class
attribute and selecting this class will give you a unique element, the right one.
Upvotes: 5
Reputation: 11383
You haven't given any context to that code, but assuming it's a method inside a View, this
refers to the View object.
this.$
is a shortcut to access jQuery from the View object, and is equivalent to the method this.$el.find
.
Upvotes: 1
Reputation: 14225
This is the same query as this.$el.find('#searchTerm').val().trim();
Upvotes: 2