1

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.

asked Jun 18, 2013 at 15:22
1

3 Answers 3

5

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.

answered Jun 18, 2013 at 16:05
Sign up to request clarification or add additional context in comments.

Comments

2

This is the same query as this.$el.find('#searchTerm').val().trim();

answered Jun 18, 2013 at 15:25

Comments

1

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.

answered Jun 18, 2013 at 15:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.