Reputation: 1363
I am learning require.js to organizing backbone.js templates. I got several tutorial when I search on internet. I found different implementations there. That's why I could not understand those codes of main.js file.
//file name main.js
require.config({
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone'
}
});
require([
'app',
], function(App)
{
App.initialize();
});
Specially I could not understand the second portion. That is
require([ 'app', ], function(App) { App.initialize(); });
What does it mean by App.initialize();?
Upvotes: 0
Views: 83
Reputation: 9597
That structure is the format for Asynchronous Module Definition, or AMD. It is basically an API for loading modules (essentially Javascript files) in your application in an asynchronous manner.
In the past, this was usually done using <script>
tags at the bottom of your page. The problem with that is those are loaded synchronously (one after another) and dealing with dependencies between the files can be onerous. AMD is one proposed standard for the ability to load your Javascript files asynchronously.
The basics are this (using your code as an example):
You invoke a function require
, which accepts two arguments:
an array of strings which represents paths to files (or aliases to paths). These would be the dependencies the file needs (think of imports in Java)
A callback function that will be called by Require after the dependencies you specified in your first argument are loaded. Require will pass in the actual files you specified in the first argument. So in your example, you are telling Require 'go and load the app.js file' and when its loaded, pass that file into my callback function
So in this code (which is your callback function) :
function(App) {
App.initialize();
}
App
represents the exposed API of the Javascript file app.js
. So when you see stuff like App.initialize()
, all that means is that the file app.js
is exposing a function called initialize that this file is invoking.
Upvotes: 0
Reputation: 3816
require([ 'app', ], // this means you have a file called app.js,
// which is a require module
], function(App) // This means after loadind, App will be an alias
// for the module.exports object
{
App.initialize(); // This means the module exposes an initialize function
// (some will call it method), that is invoked
});
Upvotes: 2