Why using the this.$(selector).method() syntax wit

2019-07-31 03:01发布

问题:

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.

回答1:

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.



回答2:

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



回答3:

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.



标签: backbone.js