I'm just getting started in Javascript, Backbone and jQuery. I am running into some code that looks like this:
someBackboneFunction: function () {
this.$('#index1').attr('disabled', 'disabled');
}
This function is declared in a backbone view subclass. From what I gather, this is referring to the function context of the object that gets created with this backbone view. The view that has this function declared is created with the new keyword. If that is correct, I'm not sure what
this.$('#index1')
actually means. Does it just mean that on the object itself that was created with the new keyword, find the index1 id and disable it? Thanks!
-
1backbonejs.org/#View-dollarmu is too short– mu is too short2013年03月25日 02:17:03 +00:00Commented Mar 25, 2013 at 2:17
2 Answers 2
this.$('#index1') is finding an element that matches the selector, #index1, as a child of the view's element itself.
For use within a view, there will be a this.$el that represents the view's element, wrapped as a jQuery object. this.$('selector') is the same as this.$el.find('selector').
4 Comments
this.$ in a Backbone view is just a fancy way of scoping the jQuery selector to the view's matching element, and not the entire document, which is the default context when using jQuery. Were you to go to any random website that has jQuery (this one included), pop open the console in the dev tools, and type in this.$('div'), you will be using jQuery the same as if you said this.$('div') or $('div'), since $ is on the root, window scope. The this in a Backbone view refers to itself-- the view. And the View object has a property called $ on it. Hope this is helping!this may reference a different object (or anything at all in strict mode) depending on how the current execution context was established. You can write this.$ only where this references an object with a $ property that references jQuery. If you don't fully understand how this works in javascript (noting that it doesn't have anything to do with scope), you should do some research (e.g. MDN).From what I remember in Backbone this.$ is a wrapper for jQuery and it allows you to select elements in the scope of your view.
So this.$('#index1') should mean "select #index1 in my view" and .attr('disabled', 'disabled') sets its disabled attribute to true.