-1
function canDeleteFacilitator(facilitatorId, handleData) {
var call = $.ajax({
    type: 'GET',
    url: urls.candeletefacilitator,
    data:{facilitatorId: facilitatorId}
}).done(function (data) {
    return handleData(data);
})
}   

var canDeleteText = "";
canDeleteFacilitator(facilitator.value, function (canDelete) {
    console.log(canDelete);
    if (canDelete == true) {
        canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
    }

})

console.log(canDeleteText);

canDeleteText does not get set within the callback function. How do I correct this scope?

Melvin
  • 925
  • 1
  • 10
  • 22
alrightgame
  • 341
  • 2
  • 7
  • 20

1 Answers1

0

You're not returning anything in your function .. You should also set the var within the scope of the function unless you're going to pass it in ... Like so ..

canDeleteFacilitator(facilitator.value, function (canDelete) {
    var canDeleteText = "";
    console.log(canDelete);
    if (canDelete == true) {
        canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
    }
    return canDeleteText;
})

In essence, canDeleteText should stay within the function .. And if you want to set it outside the function, you'll need to set as a return of the function:

var canDeleteText = canDeleteFacilitator( callbacks );

So a practical usage would be to set it as a function, off the get-go:

function canDeleteFacilitator(canDelete) {
    var canDeleteText = "";
    console.log(canDelete);
    if (canDelete == true) {
        canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
    }
    return canDeleteText;
}

var canDeleteText = canDeleteFacilitator(1); // I set it to "true" just to pass the if

console.log(canDeleteText);
Zak
  • 6,976
  • 2
  • 26
  • 48