I’m a bit confused as to where the line is for creating a new function for a task. For example, in “1.6.13 – VanillaPress V 0.3 – Toggling the Editor”, in the editor.init function you call a function (listenerEditorToggle). That function calls a helper function (getEditorToggleEl) which returns the editor toggle element and then adds the event listener, which calls the editor.toggle function to do the work.
When I wrote my version before watching the video, I replaced all of that with:
in the editor.init function (our toggle functions were about the same).
I’m just curious of the rule of thumb for deciding, “Hey this needs to be a new function”. Since the getEditorToggleEl does nothing but call the native function getElementById, isn’t it redundant to wrap it in another function? Is this for future-proofing against element name changes or something? This pattern is being used in this project for any instance where you are using getElementById.
A general rule of thumb is one function should do one thing. As parts of a function get more complex it makes sense to break them out into smaller functions.
However when to do this is always a rule of thumb and something you will get a better hand for as you go on.
However, in general event listener functions should be their own function so the event listener can be removed if needed.
In the case of the functions that get an element and nothing else, yes, this pattern is shown just in case you have a code base that you do not want to have hardcoded reference to your markup. If your markup changes you only need to update a call to that class or id in one place.
I wouldn’t say you always have to do that, but it can be helpful for certain apps 🙂