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?
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?
3 Answers
Reset to default 10You 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.
I suppose your code from React. Because recently I encounter similar issue dealing with React.
Back to your question. I think the bind
is play a transform function. Code as follow:
ponentDidMount: function() {
var _this = this;
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
_this.setState({data: data});
}
});
},
is equal to:
ponentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
});
},
As so for, I think you can understand what is the bind function and why using bind
to achieve it.
@shubham, it's the JavaScript syntax to use current this in your callback function as you mentioned in:
success: function(data){
this.setState({data: data});
}
First argument of bind()
function will act as this in calling function, you should go through apply()
and call()
functions as this would be helpful for you.