I have never been very good at understanding JS callbacks, promises and all of these. Now I stumbled on one of these scenarios.
I have a text element. When clicked, it is made editable. When pressing enter, an AJAX request is made with the input value and then (here is my issue) the original text should be updated with the input.
$('#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) {
// ???
}
});
}
});
}
You could say: simple, just take the data from the response and replace the original text with the updated one. I can't/don't want to do that because I want the edit
function to stay generic so it can be used in other scenarios, as you might have guessed by the use of the different arguments.
Also, in the context of the edit
function we don't really know the shape of the response
object, so we cannot handle it at that stage.
The right place where the response should be handled is the part where we click the text element, here we do know the context and we know the expected composition of the response
.
So essentially, I would want to return (or whatever you do when dealing with promises, callbacks, async operations...) the response from the ajax success function, fetch that response in the click handler funtion and deal with it accordingly:
$('#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"
});
I hope I could make myself understand. If I don't, please let me know so I can clarify the question.