Instead of having one big function, that gets bigger and bigger with time, you can chunk it into separate function submodules that can be added separately.
- You can plug into existing functions and enable additional features, but keep the newly added code separately.
- This way you can organise your code per "user story" or per "feature"
- You can disable the "extension" when needed for debugging.
Take a look at this simple scenario when we add a sidebar to a website. This will show you what can happen in several days when you work on your code, and how the extensibleFunction can help you to organise the code
- DAY 1: First, we only add a basic functionality, which is showing and hiding the sidebar
- DAY 2: Our product onwer asked to add a different feature: popup
- DAY 3: We found out a bug that popup overlaps the menu - we decided that before the menu is opened, all the popups should be hidden
- DAY 4: Our product owner asked to add analytics tracking
Without the extensibleFunction, on DAY 3 you would scatter your code accross different files. If you continue this proccess, after some time the initially simple function to open a sidebar will become bloated and harder to maintain.
With extensibleFunction, you can keep the fix for the popups in the same file/folder that is responsible for popups. Consider organising your folders per "user story", for example
- ShowingSidebar
- ShowingPopup
- SidebarAnalytics
-
Download the script and use it in your code
-
Declare the extensible function
showSidebar = new extensibleFunction();
- Set its core functionality
showSidebar.setCoreFunctionality(function() {
$('.sidebar').toggleClass('hidden');
});
- Bind the function wherever you want
$(document).on('click', '.sidebar-button', function() {
//this will run the function including all extensions, even if they were added later
showSidebar.run();
});
- In future you can extend the function in different place
showSidebar.extendBefore(function() {
//do something before the core functionality
});
- at the beginning
- before core functionality
- core functionality
- after core functionality
- at the end
- setCoreFunctionality
- run
Example:
showSidebar.run()
- extendAtTheBeginning
- extendBefore
- extendCore
- extendAfter
- extendAtTheEnd
You can store it in the function object under showSidebar.exportedVars
Just add your var name
showSidebar.exportedVars.yourVarName = "Your Var value"
Then this value is accessible in all other functions/extensions
console.log(showSidebar.exportedVars.yourVarName);
- Security: with the basic simple approach here, the functions are global, though it might be possible to limit their scope by namespacing. Anyway, this is probably not the best security.
- There might me more disadvantages here that I'm not aware of, since I'm not a super experienced JS dev
- For more advanced apps you probably want to see JS Module pattern