Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I think about my JavaScript application namespaces?

I'm building an app that has a single global namespace like so:

var myApp = {};

I then have a bunch of different reusable "modules" comprised of models, views and controllers.

//Bar chart module code
org.example.chart.bar.module
org.example.chart.bar.model
org.example.chart.bar.view
org.example.chart.bar.controller

I also have a big dataSource singleton and a dataManager for loading data to the dataSource:

org.example.data.dataSource
org.example.data.dataManager //populates the dataSource with CSV data

And finally translation strings and settings that should be available across the app:

org.example.static.translations
org.example.static.settings

How would you (re-)organize this so that I have easy access to the application level singletons (such as dataSource, dataManager, translations etc.) and can easily instantiate reusable modules that get scoped under the current application instance?

(Would you for example, already from the beginning, use the same namespace for your "classes" and your app? Or would you perhaps make references like so: myApp.translations = org.example.static.translations?)

like image 724
dani Avatar asked Nov 13 '22 14:11

dani


1 Answers

No we don't namespace. We write modular code and we use module loaders.

Example of a module loader would be require.js or browserify or seajs.

And an example module would be something like:

(function () {
  var jQuery = require("jQuery");
  var chart = require("chart"); 

  ...

  define("moduleName", moduleObject);
})();
like image 189
Raynos Avatar answered Dec 26 '22 10:12

Raynos