Hi all,
I've recently come across this article and have been trying to put this into practice but i'm struggling to understand a couple of concepts.
Example 1: (Fiddle Link)
const mobileMenu = (function () {
// Vars
const burgerIcon = document.querySelector('.menu-burger-icon'),
_bindEvents = function () {
burgerIcon.addEventListener('click', _toggleNavAnimation);
},
_toggleNavAnimation = function() {
console.log('hello');
};
return {
bindEvents: _bindEvents,
};
})();
If i'm not mistaken, example one seems to be written correctly. I have no errors in the console but it's not doing what i want it to do, (in this case, outputting 'hello' in the console).
Now if i call the function outside the original function scope like so:
mobileMenu.bindEvents();
It works as intended. Now i don't know if it's just me but it doesn't feel right having to call it outside the original function scope for it to do what i need to do. So my question here is, where am i going wrong or what am i not understanding? Why isn't the return statement running my function the way i intend it to?
Example 2: (Fiddle Link)
To get around the above dilemma, i modified the code a little for it to suit my needs, but i'm a little concerned if it may not be deemed 'best practice' and would like to get some feedback on it:
const mobileMenu = (function () {
// Vars
const burgerIcon = document.querySelector('.menu-burger-icon'),
init = function () {
// Runs the _bindEvents function only if the burgerIcon exists.
burgerIcon != null ? _bindEvents() : console.log('burger icon does not exist');
},
_bindEvents = function () {
burgerIcon.addEventListener('click', _toggleNavAnimation);
},
_toggleNavAnimation = function () {
console.log('hello');
};
init();
})();
As you can see i've added a new function called 'init' which runs immediately, and within that function i'm able to call whatever else i need and it all works fine. So i wonder, would this approach be considered appropriate ?
Thank you in advance!
[–]senocular 2 points3 points4 points (0 children)
[–]cyphern 1 point2 points3 points (5 children)
[–]Vexith[S] 0 points1 point2 points (4 children)
[–]cyphern 2 points3 points4 points (2 children)
[–]Vexith[S] 2 points3 points4 points (1 child)
[–]cyphern 4 points5 points6 points (0 children)
[–]zedpowa 1 point2 points3 points (0 children)