From what I understand about closures - based on for example How do JavaScript closures work? and Closures, variables declared in a closure's outer (or parent) function can be used and modified in the closure so that after the closure finishes, the variable in the outer function has the value it was last assigned in the closure.
Perhaps my understanding is incorrect, or there is something else going on in the code below that I can't quite fathom yet. 1
function showBoards(boards, outputTarget) {
$.each(boards, function (index, board) {
var brd = $("<p><span class='badge' style='background:"
+ board.prefs.backgroundColor + ";'>"
+ ((board.starred) ? "*" : " ") + "</span> "
+ board.name + "</p>");
$(outputTarget).append(brd);
});
}
function loadTheLot() {
var boards = [];
Trello.get('/members/me/boards?filter=open&fields=name,url,prefs,starred')
.success(function (response) {
$.extend(boards, response);
showBoards(boards, "#boards");
})
.error(function () { console.log("Failed to load boards.");})
;
//showBoards(boards, "#boards");
loadCardsInList("To do this week", "#todocards");
loadCardsInList("Waiting for response", "#waitingcards");
}
The extend
works as expected. When I call the showBoards
function inside the "success" closure, the output on my page neatly lists the boards that were retrieved.
When I call the showBoards
function in the closure's outer function (as the commented line shows), the page doesn't show any boards at all.
Of course the $.each
is a loop in disguise, but it is inside the a function called from the closure. As far as I understand it, there doesn't seem to be anything like the "closures in a for loop gotcha" (Aka Outer Variable Trap going on here.
Question: Why is the boards
variable declared in loadTheLot
empty again after the Trello.Get
statement.
By the way, the reason I need the boards array outside the whole Trello.get
stuff is because I want to pass the boards to the loadCardsInList function so the cards can show the board names instead of an ugly identifier.
By the way I used the get().success().error()
style because someone with what appeared a similar issue was adviced to use a "post-ajax callback" to ensure everything had finished. The style I used before had the success and error closures as the second and third parameter of the Trello.get
call.
1 I'm not exactly new to programming, but my javascript skills are very much nascent.