- // A module_id (myModule) is used here for demonstration purposes only
- define('myModule',
- ['foo', 'bar'],
- // module definition function
- // dependencies (foo and bar) are mapped to function parameters
- function ( foo, bar ) {
- // return a value that defines the module export
- // (i.e the functionality we want to expose for consumption)
- // create your module here
- var myModule = {
- doStuff:function(){
- console.log('Yay! Stuff');
- }
- }
- return myModule;
- });
- // An alternative example could be..
- define('myModule',
- ['math', 'graph'],
- function ( math, graph ) {
- // Note that this is a slightly different pattern
- // With AMD, it's possible to define modules in a few
- // different ways due as it's relatively flexible with
- // certain aspects of the syntax
- return {
- plot: function(x, y){
- return graph.drawPie(math.randomGrid(x,y));
- }
- }
- };
- });
require on the other hand is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies. An example of its usage is:
Understanding AMD: require()
- // Consider 'foo' and 'bar' are two external modules
- // In this example, the 'exports' from the two modules loaded are passed as
- // function arguments to the callback (foo and bar)
- // so that they can similarly be accessed
- require(['foo', 'bar'], function ( foo, bar ) {
- // rest of your code here
- foo.doSomething();
- });
Dynamically-loaded Dependencies
- define(function ( require ) {
- var isReady = false, foobar;
- // note the inline require within our module definition
- require(['foo', 'bar'], function (foo, bar) {
- isReady = true;
- foobar = foo() + bar();
- });
- // we can still return a module
- return {
- isReady: isReady,
- foobar: foobar
- };
- });
Tidak ada komentar:
Posting Komentar