2016-12-29 5 views
0

Я хотел бы, чтобы функция, расположенная в моем вызове ajax, имела доступ к переменной «this» в области, из которой она вызывается. Я хотел бы избежать как можно большего количества жесткого кодирования, и поэтому я должен попросить о помощи. Вот некоторые идеи.Передача объекта функции в functioncall

  • Добавить необязательный параметр в функцию ajax, которая будет отправлена ​​в качестве аргумента в обратном вызове. Это будет не очень хорошо, но это, безусловно, будет работать.
  • Отправьте ссылку на объект с помощью ajax, получите его с помощью php и отправьте его обратно, а затем получите доступ к нему через ответ. Это избавит функцию ajax, но передаст беспорядок на бэкэнд.

// Working ajax function | The problem is below this 
 
function ajax(protocol = "GET", url = "", callback = function(response){ console.log(response); }, data = null){ 
 
\t 
 
\t // Build data 
 
\t var formData = null; 
 
\t if(data !== null){ 
 
\t \t formData = new FormData(); 
 
\t \t for(var instance in data){ 
 
\t \t \t formData.append(instance, data[instance]); 
 
\t \t } 
 
\t } 
 

 
\t // Build essential ajax components 
 
\t var xhr = new XMLHttpRequest(); 
 
\t xhr.open(protocol, url, true); 
 
\t 
 
\t // Check for state updates 
 
\t xhr.onreadystatechange = function(){ 
 
\t \t if(xhr.readyState === XMLHttpRequest.DONE){ 
 
\t \t \t if(xhr.status === 200){ 
 
\t \t \t \t callback(xhr.responseText); 
 
\t \t \t } 
 
\t \t \t else{ 
 
\t \t \t \t callback("Error code: " + xhr.status); 
 
\t \t \t } 
 
     } 
 
\t } 
 

 
\t // Send it! 
 
\t xhr.send(formData); 
 
} 
 

 

 

 
// My class 
 
function MyClass(el){ 
 
    this.target = el; 
 
    this.fetch(); // Call the fetch method 
 
} 
 
MyClass.prototype.fetch(){ 
 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 
 
    
 
    
 
    ajax("POST", "target/path.php", function(response){ 
 
    var newEl = document.createElement("div"); 
 
    newEl.innerHTML = response; 
 
    
 
    // HERE's THE RPOBLEM 
 
    this.target.appendChild(newEl); // "this" refers to the window object.. 
 
    
 
    }, {data: "data"}); 
 
} 
 

 
var myTarget = document.getElementById("myTarget"); 
 
var myInstance = new MyClass(myTarget);
<div id="myTarget"></div>

+0

Возможная Дубликат [JavaScript, как получить this.variable в функции обратного вызова] (http://stackoverflow.com/questions/14670359/javascript -how-to-get-this-variable-in-callback-function) – skyline3000

ответ

1

Есть несколько решений для вашей проблемы

1) Вы можете создать замыкание

MyClass.prototype.fetch(){ 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 

    var that = this; 

    ajax("POST", "target/path.php", function(response){ 
    var newEl = document.createElement("div"); 
    newEl.innerHTML = response; 

    // HERE's THE RPOBLEM 
    that.target.appendChild(newEl); // "this" refers to the window object.. 

    }, {data: "data"}); 
} 

2) Вы можете использовать bind method

MyClass.prototype.fetch(){ 
    this; // "This" works perfectly in this scope as it refers to myInstance in this example 


    ajax("POST", "target/path.php",(function(response){ 
    var newEl = document.createElement("div"); 
    newEl.innerHTML = response; 

    // HERE's THE RPOBLEM 
    this.target.appendChild(newEl); // "this" refers to the window object.. 

    }).bind(this), {data: "data"}); 
} 
1

может хранить:

var context = this; 

Внутри функции обратного вызова, контекст использования ... Ваш это имеет в виду окно, так как она вызывается окно объектов функции (ваша функция AJAX). Кстати, ваш код является неправильным (прототип Декабре):

MyClass.prototype.fetch=function(){ 
var context=this; // "This" works perfectly in this scope as it refers to myInstance in this example 
ajax("POST", "target/path.php", function(response){ 
var newEl = document.createElement("div"); 
newEl.innerHTML = response; 
// HERE's NOT THE RPOBLEM 
context.target.appendChild(newEl); // "context" refers to the MyClass Object object.. 
}, {data: "data"}); } 
+0

Спасибо! Я упростил свой код без его тестирования, поэтому метод был неправильным. –

Смежные вопросы