copenndthagen
copenndthagen

Reputation: 50742

Meaning of keyword "this" in jQuery Vs MVC

I am trying to understand the difference of using the keyword "this" or rather what it represents in jQuery Vs an MVC framework like Backbone.

Below are 2 code samples of each; So in jQuery, we have

$("#result").click(function(){
$(this).html(someval);
})

In Backbone, we have code as;

var HandlebarsView = Backbone.View.extend({
el: '#result'
initialize: function(){
this.template = Handlebars.compile($('#template').html());     
},
render: function(){
var html = this.template(this.model.toJSON());
this.$el.html(html);
}
});

Now I do understand that "this" refers to the DOM element in jQuery.

I wanted to understand what it represents in case of the Backbone code.

Please let me know.

Upvotes: 6

Views: 269

Answers (2)

Derick Bailey
Derick Bailey

Reputation: 72868

this is the context in which a function executes.

The trick to understanding this is understanding that it's the way you execute a function that determines it.

When you pass a function to a method like jQuery, you are using that function as a callback method. jQuery explicitly sets the context of the callback when it executes.

When you call a method on an object using the dot-notation: myView.render() it's the dot-notation that explicitly sets the context of the method call to the object in front of the dot.

The rules for what a context is set to are pretty simple in JavaScript, but can cause a lot of confusion. Most languages set the self-referencing context variable to the object that the method was defined in. JavaScript, though, uses the method invocation pattern to determine the context.

When we pass a any object's method around as a callback method, the code that calls it sets the context of the method - this includes Backbone's views and other objects. You can explicitly override this by using Underscore.js' bind and bindAll functions ( http://documentcloud.github.com/underscore/#bind ), as well as a few other tricks.


Backbone.View.extend({
  initialize: function(){
    _.bindAll(this);
  }
});

This code, for example, will bind the context of all the functions on the current view object, to the view. This guarantees that the context of your view methods will always be the view itself.

For more info see:

Upvotes: 3

websymphony
websymphony

Reputation: 303

In Backbone 'this' inside the view refers to the current view object. In models 'this' refers to the current model object. And similarly for collections 'this' refers to the current collection object.

But for views 'this' is transient between selected dom element by jQuery and view object, that is why we use _.bindAll function so that we can make sure that 'this' remains the current view object when we are calling certain functions like 'render', etc. See http://documentcloud.github.com/underscore/#bindAll

Upvotes: 1

Related Questions