purpose of .bind(this) at end of ajax callback?

AjaxReactjs

Ajax Problem Overview


From the reactjs tutorial, what's the purpose of having .bind(this) at the end of the ajax callback? Does code work correctly without it?

        data: JSON.stringify({text: text}),
        success: function (data) {
            this.setState({data: data});
        }.bind(this),

Ajax Solutions


Solution 1 - Ajax

It ensure's this will be the correct object inside the callback. See Function.prototype.bind().

An alternative specific to react is to do:

myAjaxFunction: function(){
  $.getJSON('/something', this.handleData);
},
handleData: function(data){
  this.setState({data: data});
}

This works because React handles binding of component methods for you.

If you ran your original code in without bind, you'd get this error: TypeError: undefined is not a function because this === window in the callback;

or in strict mode: TypeError: Cannot read property 'setState' of undefined, where this === undefined in the callback.

Solution 2 - Ajax

The purpose of having .bind(this) at the end of the ajax callback is let this be related to your react class. In other words you can add:

var self = this;

outside of ajax and it works the same. You code equal to:

var self = this;
$.ajax({
	.
	.
	data: JSON.stringify({text: text}),
	success: function (data) {
		self.setState({data: data});
	},
	.
	.
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionferk86View Question on Stackoverflow
Solution 1 - AjaxBrigandView Answer on Stackoverflow
Solution 2 - AjaxChaosPredictorView Answer on Stackoverflow