Monday, 9 September 2013

How do you ensure closures use new variables each time?

How do you ensure closures use new variables each time?

I have a "check in" function on my app where after checking in once, the
rest of the checkins are bound to that same element...even though I think
I'm using the closure correctly. Here's the basic version of the logic I
have:
var elements = [{name: "name", info: info}, {name: "anothername", info:
moreinfo}];
$(document).ready(function() {
for (var i in elements) {
insertHTML(elements[i])
}
}
function insertHTML() {
var check_in_element = $('<div class="check_in"></div>')
$('#main').append(check_in_element)
check_in_element.bind('click', function(e) {
$(this).css('color', 'red');
check_in(e);
}
}
function check_in(e) {
var information = getInformation(e); // not asynchronous, information
is OK here
getCurrentPosition( function(response) {
onLocationFound(response, information); // information is WRONG
here! It is referring to the first click
}, function(error) {
console.log('error');
});
}
function onLocationFound(response, information) {
// I want to use "information" in this callback, but it's referring
// to the LAST "information" variable (the first time the check in was
tapped)
// WHY?
}
function getInformation(e) {
return e.stuff
}
What's the best way to structure this logic so that it WORKS? Thank you!

No comments:

Post a Comment