最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JQuery bind on Ajax success - Stack Overflow

programmeradmin4浏览0评论

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?

Share Improve this question edited Sep 4, 2020 at 20:24 user4035 23.7k11 gold badges65 silver badges101 bronze badges asked Feb 23, 2015 at 10:06 shubhamshubham 1,3192 gold badges12 silver badges26 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

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.

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.

发布评论

评论列表(0)

  1. 暂无评论