The value of the keyword "this" in jQuery Vs MVC

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

Below are 2 sample code for each of them; So in jQuery we have

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

In Backbone, we have code like:

 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 understand that "this" refers to the DOM element in jQuery.

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

Please let me know.

+6
source share
2 answers

this is the context in which the function is executed.

The trick to understanding this is to understand that it has a function that defines it.

When you pass a function to a method like jQuery, you use that function as a callback method. jQuery explicitly sets the callback context when it is executed.

When you call an object method using dot notation: myView.render() is a dot notation that explicitly sets the context of the method call before the object before the dot.

The rules for setting context are pretty simple in JavaScript, but can cause a lot of confusion. Most languages ​​set a self-regulatory context variable to the object in which the method was defined. However, JavaScript uses a method invocation template to determine the context.

When we pass an object method as a callback method, the code calling it sets the context of the method - this includes baseline views and other objects. You can explicitly override this using the Underscore.js bind and bindAll ( http://documentcloud.github.com/underscore/#bind ), as well as several other tricks.

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

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

For more details see:

+3
source

In Backbone, 'this' inside a view refers to the current view object. In models, 'this' refers to the current model object. Similarly for collections, 'this' refers to the current collection object.

But for views, 'this' is a transient between the selected dom element using jQuery and the view object, so we use the _.bindAll function so that we can make sure that 'this' remains the current view object when we call certain functions, such as "rendering" etc. See http://documentcloud.github.com/underscore/#bindAll

+1
source

Source: https://habr.com/ru/post/911190/


All Articles