module.exports = 'A';
module.exports = 'B';
var moduleA = require('A'), moduleB = require('B'); module.exports = moduleA + moduleB + 'C';
var moduleC = require('C'); console.log(moduleC); // prints "ABC"
define('A', function() { return 'A'; });
define('B', function() { return 'B'; });
define('', ['A', 'B'], function(moduleA, moduleB) { return moduleA + moduleB + 'C'; });
require([''], function(moduleC) { console.log(moduleC); // prints "ABC" });
modules.define('A', function(provide) { provide('A'); });
modules.define('B', function(provide) { provide('B'); });
modules.define('C', ['A', 'B'], function(provide, moduleA, moduleB) { provide(moduleA + moduleB + 'C'); });
modules.require([''], function(moduleC) { console.log(moduleC); // prints "ABC" });
setTimeout
. With the help of YM, the previous example can be easily rewritten as follows (which cannot be expressed either by CommonJS or AMD, although the latter even contains Asynchronous in the title, but it only affects the declaration method and the method of requiring the module): modules.define('A', function(provide) { setTimeout(function() { provide('A'); }); });
modules.define('B', function(provide) { setTimeout(function() { provide('B'); }); });
modules.define('C', ['A', 'B'], function(provide, moduleA, moduleB) { provide(moduleA + moduleB + 'C'); });
ymaps.ready
. Our project is quite complicated, and we use quite a lot of inheritance from the base classes from api. Consider the example of one of them. We have our own layer class ComplexLayer, which we want to inherit from the base layer of ymaps: ymaps.Layer
. With the help of YM, this is done simply: we define the module ymaps, which loads the API, then it waits for the desired event (ymaps.ready) and then it will provide itself. All modules that depended on the api module (ymaps) begin their rezolving only after that. Thus, our modules, again, do not know anything about the asynchronous nature of the Yandex.Maps API. No crutches in the code! modules.define( 'ymaps', ['loader', 'config'], function(provide, loader, config) { loader(config.hosts.ymaps + '/2.1.4/?lang=ru-RU&load=package.full&coordorder=longlat', function() { ymaps.ready(function() { provide(ymaps); }); }); });
modules.define('ComplexLayer', ['inherit', 'ymaps'], function(provide, inherit, ymaps) { var ComplexLayer = inherit(ymaps.Layer, ...); provide(ComplexLayer); });
modules.define( 'jquery', ['loader', function(provide, loader) { loader('//yandex.st/jquery/2.1.0/jquery.min.js', function() { provide(jQuery.noConflict(true)); }); });
void modules.define( String moduleName, [String[] dependencies], Function( Function(Object objectToProvide) provide, [Object resolvedDependency, ...], [Object previousDeclaration] ) declarationFunction )
void modules.require( String[] dependencies, Function( [Object resolvedDependency, ...] ) callbackFunction )
Source: https://habr.com/ru/post/213627/
All Articles