Butterfly JS Module Loader documentation

loader is a module loader used by Butterfly and usable by your application. With it, you can load different modules of your application to then use them in other modules.

Using modules allows you to separate the layers of your code without exposing everything to the global scope while making everything testable.

The loader allows developers to either directly execute a module without saving it, this is useful for entry point modules for example; to load a module to then use it by another module or to get a loaded module, for example to use Butterfly out of the modules system (cf Butterfly examples).

However, the loader will not automatically include files. A module must be explicitely included before being usable in the application.

addModule(moduleName, dependencyModule1, dependencyModule2, ..., dependencyModuleN, module)

This method loads a module to be executed later. The first argument is the module name, this name is then used to access the module or inject it in another module as a dependency. The last argument is the module itself. It must be a function containing the module's code. The arguments in between are the names of the modules the current one needs to run.

The added module's function must return the module itself, it can be of any needed type.

The module gets as arguments its depending modules, in the same order as provided in the executeModule call.

Example

loader.addModule('Car', function () {
	var Car = function (brand) {
		this.brand = brand;
	};

	return Car;
});

loader.addModule('Garage', 'Car', function (Car) {
	var cars = [],
		Garage = {
			addCar: function (carBrand) {
				cars.push(new Car(carBrand));
			},

			getCars: function () {
				return cars;
			}
		};
});

executeModule(moduleName, dependencyModule1, dependencyModule2, ..., dependencyModuleN, module)

This method directly executes a module provided in the arguments. The arguments of executeModule are the same as addModule. The only difference is that the module name is not used and is here only for readability purposes.

Example

If we reuse our example from addModule, we can make a following 3rd module

loader.executeModule('myCarApp', 'Garage', function (myGarageModule) {
	myGarageModule.addCar('BWM');
	myGarageModule.addCar('Fait');
	myGarageModule.addCar('Arton Mastin');

	var cars = myGarageModule.getCars(),
		c;
	for (var c = 0; c < cars.length; c++) {
		console.log(cars[c].brand);
	}
});

getModule(moduleName)

If you want to use a module out of the module system (for example Butterfly), you can get a loaded module and use it directly.

Example

To use Butterfly without using a module, you can do:

<script type="text/javascript" src="url/to/butterfly.min.js"></script>
<script type="text/javascript">
var B = loader.getModule('B');
console.log(B.$id('someId'));
</script>