7

I understand that define is used to define a module, and function is an anonymous function, but what does the argument 'require' in the function hold?

If I write anything in define(function(require){...}), when will this be called? How to give a call to his anonymous function?

Please help, I am new to advanced JS.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Tehreem
  • 476
  • 9
  • 23
  • 2
    Did you try to learn more about how does this work in RequireJS documentation? – Matías Fidemraizer Oct 07 '14 at 05:50
  • 1
    Ya, i read about RequireJS, but there they are using require(), as a function, and not as an argument. I dint understand that when its passed as an argument `function(require)` , what is actually passed in require? – Tehreem Oct 07 '14 at 06:03
  • 1
    possible duplicate of [What is define used for in Javascript (aside from the obvious)](http://stackoverflow.com/questions/10331305/what-is-define-used-for-in-javascript-aside-from-the-obvious) – Artjom B. Mar 29 '15 at 15:51

1 Answers1

6

This is part of the requireJs api, it's not vanilla JS.

You can see the full docs in here: http://requirejs.org/docs/api.html#define

"require" in the above example is actually the "require" code, this pattern allows you to require a JS and, than only when loading the JS is completed, load yet another dependency, but do so in the scope of the previously required file.

At large, this pattern allows you to break your app into multiple small JS files, and load them in an async way to speed up the loading process of web pages.

Some would argue that this is all going to be less needed when SPDY and HTTP2 are going to be more widely used. In any case, this is surely promotes a better modularity in the code design.

JAR.JAR.beans
  • 9,668
  • 4
  • 45
  • 57
  • `define(function (require) { var angular = require('angular'); var html = require('text!./productPage.html'); var css = require('css!./productPage'); var productDesc = require('./../productDesc/productDesc'); }); ` This is the code, here in the `function(require)`, is it the same as `require(some text)`? And when will this particular function be called from the html page? – Tehreem Oct 07 '14 at 06:09
  • It's not the same. the require is a callback, so is called only when the internal implementation of require is ready to call this. if you just do, require(some text), it means the method is being called immediately, the requireJs code may or may not be ready to be called at that point. – JAR.JAR.beans Oct 07 '14 at 06:20
  • I tried printing require in console.log, i got the following: `function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return } ` – Tehreem Oct 07 '14 at 06:56