swennemen
swennemen

Reputation: 955

Reference to HTML elements in view, a convention?

I'm currently in the progress of learning Backbone.js and I'm using the book Developping Backbone Applications.

I have a questions about the reference to HTML elements and how they are stored. For example:

   initialize: function() {
        this.$input = this.$('#new-todo');

Here the HTML element with ID to-do is stored in the this.$input, why do we use the $ in front of input, is this merely a convention? If I change this.$input to this.input my code works fine. I find this confusing because the book states:

The view.$el property is equivalent to $(view.el) and view.$(selector) is equivalent to $(view.el).find(selector).

I would think that $(view.el) does something completely different than (view.el).

How is this.$input saved in Backbone.js? If I console.log it, it produces:

Object[input#new-todo property value = "" attribute value = "null"]

Could someone give me some insight? :)

Upvotes: 0

Views: 72

Answers (1)

Manish Mulimani
Manish Mulimani

Reputation: 17615

  • Using $ infront of a variable name is just a naming convention. It helps developer in distinguishing variable holding jQuery objects from others.

  • view.$el is a helper variable provided by Backbone, so that we can use it directly, instead of explicitly forming the jQuery object. Hence view.$el is equivalent to $(view.el).

view.$el is assigned in setElement method:

setElement: function(element, delegate) {
   // Some code
   this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
   // Some code
}

Backbone.$ is reference to $ global variable exported by jQuery.

  • view.$(selector) is a method defined in View. It's definition does exactly same as $(view.el).find(selector)

    $: function(selector) { return this.$el.find(selector); }

Upvotes: 1

Related Questions