Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ajax

reactjs

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), 
like image 677
ferk86 Avatar asked Jun 18 '14 12:06

ferk86


People also ask

What is the purpose of callback function in Ajax explain with examples?

Description. The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.

What does an Ajax call return?

ajax() (and various ajax shortcut methods) returns a jqXHR object, which is a superset of the browser's native XMLHttpRequest object and implements inter alia the Promise interface.


1 Answers

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.

like image 171
Brigand Avatar answered Sep 22 '22 18:09

Brigand