This issue has nothing to do with scopes - it has to do with when code is run. Asynchronous code is asynchronous and this problem is the same as incorrectly assigning a variable in an AJAX call.
Take the following code (where I have corrected the assignment to the non-existent "clickedbtn" variable) which indicates when things will run by per the numbers in the comments:
# 1
var clicked = "initial value";
# 2
$("button[role=remove]").click(function() {
# At some point -AFTER- 3
clicked = this.id;
alert(clicked);
});
# 3
alert(clicked);
This is because the click callback is only called after the user clicks the button (read: "at some point in the future") while the .click
function to add the callback handler returns immediately and the following code to display the alert is executed immediately which happens before the variable has been assigned the ID of the element which may be clicked in the future.