2015-09-19 56 views
1

我有這樣的代碼:如何將對象傳遞給jquery回調?

function API() { 
    this.status = 'nothing'; 
} 

API.prototype.search = function() { 
    this.status = 'searching'; 

    $.ajax({ 
     url: 'https://api.com', 
     data: {shapeFormat: 'raw'}, 
     dataType: 'json', 
     timeout: 11000, 
     success: this.OK_callback, 
     error: this.KO_callback 
    }); 
} 

API.prototype.OK_callback = function(data) { 
    console.log(this.status); // How to pass this value to the function? 
} 

API.prototype.KO_callback() { 
    this.status = 'done'; 
} 

我怎麼能訪問this.status值insie OK_callback? 在此先感謝!

回答

1

您需要在適當的上下文中調用您的函數。簡單的方法是使用Function.prototype.bind方法:

$.ajax({ 
    url: 'https://api.com', 
    data: {shapeFormat: 'raw'}, 
    dataType: 'json', 
    timeout: 11000, 
    success: this.OK_callback.bind(this), 
    error: this.KO_callback.bind(this) 
}); 

,或者您可以使用context設置來設置回調背景:

$.ajax({ 
    url: 'https://api.com', 
    data: {shapeFormat: 'raw'}, 
    dataType: 'json', 
    timeout: 11000, 
    success: this.OK_callback, 
    error: this.KO_callback, 
    context: this 
});