2015-02-23 60 views
8

为什么我们调用bind Ajax的成功调用 看看这个代码JQuery的绑定

$.ajax({ 
     url: myurl, 
     dataType: 'json', 
     success: function(data) { 
     this.setState({data: data}); 
     }.bind(this) 

,如果我们不调用bind,便无任何区别还是存在的优势在这里使用绑定

回答

8

您需要致电bind()以强制您的回调上下文(this)是正确的。否则,默认情况下会在全局上下文中调用它(显然,jQuery使用jqXHR对象的上下文调用它)。 bind()将函数的上下文设置为任何this应该是。

+0

对不起,我没有得到这个。请你详细说明 – shubham 2015-02-23 10:25:13

+2

如果你不调用bind,回调里面的'this'将是错误的。 – Scimonster 2015-02-23 10:25:52

1

@shubham,因为你在

success: function(data) { 
    this.setState({data: data}); 
    } 

提到其JavaScript语法使用当前这在回调函数,绑定的第一个参数()函数将在调用函数充当这个,你要跟应该通过apply()和call()函数会对你有所帮助。

0

我Scimonster.bind()同意设置到任何这应该是你的功能的情况下,或者你的功能会给这样的错误:遗漏的类型错误:this.setState不是一个函数

1

我想你的代码从反应。因为最近我遇到类似的问题,处理反应

回到你的问题。我认为bind发挥转换功能。代码如下:

componentDidMount: function() { 
var _this = this; 
$.ajax({ 
    url: this.props.url, 
    dataType: 'json', 
    cache: false, 
    success: function(data) { 
    _this.setState({data: data}); 
    } 
}); 
}, 

等于:

componentDidMount: function() { 
$.ajax({ 
    url: this.props.url, 
    dataType: 'json', 
    cache: false, 
    success: function(data) { 
    this.setState({data: data}); 
    }.bind(this) 
}); 
}, 

至于所以,我想你能明白什么是绑定功能和使用为什么要bind实现它。