Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 657
copenndthagen Avatar asked Mar 20 '12 11:03

copenndthagen


1 Answers

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:

  • http://es5.github.com/ - annotated ES5 specification
  • http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/
  • http://lostechies.com/derickbailey/2011/06/15/solving-backbones-this-model-view-problem-with-underscore-js/
  • http://www.watchmecode.net/javascript-context (my own screencast covering all the rules and how to use them - a paid screencast)
like image 154
Derick Bailey Avatar answered Sep 20 '22 17:09

Derick Bailey