Reputation: 5520
I have this code:
function dialogTexts(message) {
var langText = $.ajax({
type: 'GET',
url: '/index.php/main/dialogtexts',
dataType: 'json'
});
langText.done(function(data) {
message(data);
});
langText.fail(function(ts) {
alert(ts.responseText);
});
}
dialogTexts(function(text) {
alert(text.delete);
});
I'm using a callback to alert the string text.delete (in above code), but I want to do something like:
dialogTexts(function(text) {
return text;
});
var deleteConfirmationDialogText = dialogTexts.delete;
alert(deleteConfirmationDialogText); //deleteConfirmationDialogText is undefined
Upvotes: 0
Views: 368
Reputation: 708056
dialogTexts
is a function and it does not have a property .delete
. That's why dialogTexts.delete
is undefined
when you try to use it. You simply can't use the kind of shortcut you're trying to do.
Also, the return statement in here:
dialogTexts(function(text) {
return text;
});
is doing nothing. It's just returning to the caller of that callback which is inside of dialogTexts()
and that caller is not doing anything with the return value so return text
is doing nothing.
If you want to alert the text, you will have to do what you first had:
dialogTexts(function(text) {
alert(text.delete);
});
That is the only real way to do it and this is a consequence of how asynchronous programming works with AJAX calls. There are some other techniques for handling callbacks (such as promises), but they all require you to process the asynchronously returned data in a callback function. That's just the nature of asynchronous programming.
Upvotes: 1