I’m struggling with closure scope in a JavaScrit function. The function below should create three swatches with different images (which works), then when these are clicked, should switch the stylesheet.
The problem is that the same object is passed to the switchTheme function even though stepping through shows the theme variable in the first function does change.
var switcherConfig = {
themes:
{
'Orangeness': {
folder: 'ui-lightness'
},
'Red Matter': {
folder: 'blitzer'
},
'Flubber': {
folder: 'south-street'
}
}
}
function createThemeSwitcher(placeholderSelector) {
for (var themeName in switcherConfig.themes) {
var theme = switcherConfig.themes[themeName];
var anchor = $('<a/>')
//.text(theme.title)
.attr('title', theme.title)
.attr('href', '#')
.on('click', function () { switchTheme(theme); })
// append to DOM etc
}
}
function switchTheme(theme) {
var themeDirectory = switcherConfig.baseDirectory + '/' + theme.folder + '/';
// 'theme' variable is always the last in my 'themes' config object
}
The value used by
switchTheme(theme)will be the state thatthemeis in when the function is called, the value is not bound at the moment you create that anonymous callback. Use a closure to bind that particular value: