Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this.$('.selector') do in jQuery?

I see this in someone's code: this.$('.selector') and am curious what that does. "this" is a Backbone view. So what does prefixing "this." onto a jQuery selector, in the given context, do?

like image 296
Chad Johnson Avatar asked Sep 28 '12 16:09

Chad Johnson


2 Answers

From the doc:

$ (jQuery or Zepto)view.$(selector)

If jQuery or Zepto is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes. It's equivalent to running: view.$el.find(selector)

ui.Chapter = Backbone.View.extend({
  serialize : function() {
    return {
      title: this.$(".title").text(),
      start: this.$(".start-page").text(),
      end:   this.$(".end-page").text()
    };
  }
});

In short, it's used to access some elements of View with a familiar syntax.

like image 66
raina77ow Avatar answered Nov 18 '22 20:11

raina77ow


It is basically limiting the search for elements with a class of selector to the element your View is based off of.

like image 24
Jack Avatar answered Nov 18 '22 22:11

Jack