Organizing Javascript codes with namespacing
Usually when I build website each page has it's own Javascript file. But as the site grows I find it hard to maintain and code duplication is every where. After a few googling and research I found out that Javacript namespacing is the best way to organize and modularize your code. With my current hybrid app I have to constantly communicate with SQLite and that's how I realize I have to reuse code blocks to avoid spaghetti code. What I did is something like this.
Let's break it down into pieces.
Let's break it down into pieces.
- Line one - we create a closure and import jQuery object so we can use it inside our namespace. You can remove the dollar sign ($) if you don't need it. Make sure you remove 'jQuery' at line 25 too.
- Line two - we declare a global object variable 'APP'. This is our namespace.
- Line four - we put a sub-namespace called SQL. Basically this a namespace inside a namespace. cool isn't.
- Line 5 - we declare a function named 'insert' with parameter 'data'. We can now call this function by calling our namespace and it's sub-namespace like this: APP.SQL.insert(mydata);
- We can put any number of functions inside our namespace, remember to put comma in between function just like what we did on line eight.
- Line fifteen - We declare another sub-namespace called 'HELPER'. The list can go on as much as you need
Try to use a module system like AMD, CommonJS or ES6 modules. Dependency management is way more better than just namespacing, where things could clash.
ReplyDeleteI guess I've read about AMD before, something about requirejs but didn't pay much attention about it. Thanks for the tip. I'll look into it and maybe post something about it.
DeleteI personally use CommonJS with browserify, it's simple and easy.
DeleteWhat Satyajit mentioned would be better than namespacing, but besides that I noticed a few things. You are using a closure and then explicitly setting window.APP, then when you set everything on APP you are implicitly implying it is on window. If the closure was called with something other than window as the scope or APP was already defined in the scope, but not globally (on window) it would not work. You will also override window.APP if it is already set. I would suggest something like `var APP = window.APP = window.APP || {};`
ReplyDeleteThanks for the pro tip. You're really good. I'll try your scenario and update my code. Right now I'm sticking with namespacing. Isn't declaring var will make my APP variable local?
DeleteAPP points to window.APP, so it will be fine.
DeleteOh yes. You're right. Big Thanks. Cheers!
DeleteThis comment has been removed by the author.
Delete