I’m only started to understand closures when suddenly it throws me another curveball, making my understanding of the scoping in closures even worse. I have a relatively simple closure just so I can get jQuery working inside of an object, which is then called by event handlers outside.
var cwn = (function($) {
var app = {
overlay: {
e: "#sidebar-overlay",
activate() {
$(this.e).fadeIn();
$('body').css('overflow', 'hidden');
},
deactivate() {
$(this.e).fadeOut();
$('body').css('overflow', 'unset');
},
},
sidebar: {
e: '#sidebar',
open() {
app.overlay.activate();
$(this.e).animate({"width": 'show'});
},
close() {
app.overlay.deactivate();
$(this.e).animate({"width": 'hide'}, 'fast');
}
}
};
return app;
})(jQuery);
So using it in the console itself or calling the function without the event handlers, results in it working – the sidebar activates and opens up and does what it’s supposed to.
cwn.sidebar.open(); // THIS WORKS JUST FINE
However using this said function with an event handler results in this
changing.
$('.hamburger-link').on('click', cwn.sidebar.open); // THIS CHANGES 'this' TO SOMETHING ELSE
Which then causes it to fail.
I have an interim solution – which is to replace this.e
with app.sidebar.e
but that just seems extremely cumbersome and it just seems to me that there is a better and simpler solution out there.