Why do we call bind on AJAX success
calls?
Take a look at this code:
$.ajax({
url: myurl,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this)
});
If we don't call bind
, then does it makes any difference or there is an advantage to use bind
here?
You need to call bind()
in order to force your callbacks context (this
) to be the right thing. Otherwise, it is called in the global context by default (apparently, jQuery calls it with a context of the jqXHR object). bind()
sets the context of your function to whatever this
is supposed to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With