2017-04-20 42 views
0

我從來沒有很好的理解JS回調,承諾和所有這些。現在我偶然發現了其中一種情況。jQuery回調後,由另一個功能請求

我有一個文本元素。點擊後,它可以編輯。當按Enter鍵時,AJAX請求會與輸入值一起進行,然後(這是我的問題)原始文本應該用輸入進行更新。

$('#text-element').click(function() { 
    edit($(this), url, paramName); 
}); 

function edit($element, url, paramName) { 
    // show the input, set up some UI events... 

    $input.keypress(function(key) { 
     // check if it is the correct key to submit the data 
     if (submit) { 
      var data = {}; 
      data[paramName] = $input.val(); 
      $.ajax({ 
       url: url, 
       method: 'post', 
       data: data, 
       success: function(response) { 
        // ??? 
       } 
      }); 
     } 
    }); 
} 

你可以這樣說:簡單的說,就是從響應中取出數據並用原來的文本替換原來的文本。我不能/不想這樣做,因爲我希望edit函數保持通用,以便可以在其他場景中使用它,正如您可能已經通過使用不同參數所猜測的那樣。

此外,在edit函數的上下文中,我們並不真正知道response對象的形狀,所以我們無法在該階段處理它。

響應應該被處理的正確位置是我們點擊文本元素的部分,在這裏我們知道上下文,並且我們知道response的預期組成。

所以基本上,我會想(或任何你承諾,回調,異步操作打交道時做...)從阿賈克斯成功函數的響應,取單擊處理程序funtion和協議,響應與它相應:

$('#text-element').click(function() { 
    edit($(this), url, paramName); // <--- this should "return" the response 
    var response = ...; // how do I fetch this response from the edit function 
    $(this).html(response.content); // the response we expect in this case would be a JSON response with a key "content" 
}); 

我希望我能讓自己明白。如果我不知道,請讓我知道,這樣我可以澄清這個問題。

+0

爲什麼你在另一個事件處理程序中綁定事件處理程序? – Satpal

+0

什麼是'$ input'?無論如何,'$ element'參數將引用原始文本元素。 – nnnnnn

+0

@Satpal我不明白你在問什麼。 – dabadaba

回答

1

簡單地做一個回調函數:

$('#text-element').click(function() { 
    edit($(this), url, paramName,function(response){ 
     this.html(response.content); 
    }.bind($(this)));//bind to keep the #text-element as this 
}); 

function edit($element, url, paramName,callback) { 
// show the input, set up some UI events... 

$input.keypress(function(key) { 
    // check if it is the correct key to submit the data 
    if (submit) { 
     var data = {}; 
     data[paramName] = $input.val(); 
     $.ajax({ 
      url: url, 
      method: 'post', 
      data: data, 
      success: function(response) { 
       callback(response);//whats your problem with callbacks? they are so easy... 
      } 
     }); 
    } 
}); 
} 

順便說一句,如果用戶點擊了兩次,有註冊了兩個按鍵處理,使得整個代碼一團糟。所以你可能會以某種方式阻止...

+0

'this'似乎並不是一個jQuery,因爲我在'edit'函數中調用了'$ el.width',並且我得到了「它不是一個函數」的消息,這意味着它不是一個jQuery實例。 – dabadaba

+0

@dabadaba oops,看起來像你是對的。編輯 –

+0

@dabadaba nope。這應該基於你發佈的代碼工作。err必須在其他地方... –