Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery bind on Ajax success

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?

like image 881
shubham Avatar asked Feb 23 '15 10:02

shubham


1 Answers

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.

like image 143
Scimonster Avatar answered Sep 23 '22 10:09

Scimonster