The collection of the article is very good, unfortunately, some still do not understand the amount ... Requirejs Advanced: Definition and loading of modules

Source: Internet
Author: User
Tags define function

textRequirejs Advanced: Definition and loading of modules
    • Javascript
    • Requirejs
Two instruments released December 01, 2014
    • Recommended 4 Recommendations
    • Collection 15 Favorites,6.9k browsing
Overview

The module differs from the traditional script file, and it defines a scope well to avoid global namespace contamination. It can explicitly list its dependencies and inject those dependencies in the form of a function (the function that defines the module), without referencing global variables. The Requirejs module is an extension of the module pattern, with the benefit of not having to refer to other modules globally.

Requirejs's module syntax allows it to load multiple modules as quickly as possible, although the order of loading is variable, but the order of dependencies is ultimately correct. And because you don't need to create global variables, you can even load different versions of the same module on the same page.

(If you are familiar with CONMMONJS, see Commonjs's Annotated information for Requirejs module mapping to the COMMONJS module).
A disk file should only have 1 modules defined. Multiple modules can be packaged using built-in optimization tools.

Definition of a module simple key-value pairs

If a module contains only value pairs and no dependencies, then the values are defined in define ():

define({    name: "john", age : 20, sex : "femal"});

Comments: This situation is not very useful, it is generally used for simple data simulation. After the module is loaded, the parameter injected in the callback function is the key-value pair object, which is:

{    name: "john", age : 20, sex : "femal" }
Function-Defined

If a module does not have any dependencies, but requires a function to do the setup work, define the function in define () and pass it to define ():

define(function () {    //Do setup work here    return {        color: "black", size: "unisize" }});

Comments: This is suitable for non-dependent module writing, and the parameters injected in the callback function are determined by the return value of return in the function, and if there is no return statement, the default is to return undefined.

A functional definition of the existence of a dependency

If the module has a dependency: the first parameter is an array of dependent names, and the second argument is a function that is called to define the module after all dependencies of the module have been loaded, so the module should return an object that defines the module. The dependency is injected into the function as a parameter, and the argument list corresponds to the dependent name list one by one.

//my/shirt.js now has some dependencies, a cart and inventory//module in the same directory as shirt.jsdefine(["./cart", "./inventory"], function(cart, inventory) { //return an object to define the "my/shirt" module. return { color: "blue", size: "large", addToCart: function() { inventory.decrement(this); cart.add(this); } } });

This example creates a My/shirt module that relies on My/cart and my/inventory. The files on the disk are distributed as follows:

    • My/cart.js
    • My/inventory.js
    • My/shirt.js

The module function uses the parameters "cart" and "inventory" to use both of the modules specified with the name "./cart" and "./inventory". The module function is not called until the two modules have been loaded.

Modules are severely discouraged from defining global variables. Following the definition pattern here, you can make different versions of the same module coexist on the same page (see Advanced usage). In addition, the order of the parameters should be consistent with the dependency order.

The returned object defines the "My/shirt" module. In this definition mode, "My/shirt" does not exist as a global variable.

Reviews: This is the most common usage in the module. Take note of the above highlighted section.

Define a module as a function

The return value type of the module is not mandatory to be an object, and the return value of any function is allowed. Here is a module definition that returns a function:

A module definition inside foo/title.js. It usesMy/cart and My/inventory modules from before,But since foo/title.js are in a different directory thanThe "my" modules, it uses the "my" in the module dependency//name to find them. The "my" part of the the name can be Mapped//to any directory, but by default, it's assumed to be A//sibling to the "foo" Directory.define ([ "My/cart",  "My/inventory", function (cart, inventory) {//return a function to define "Foo/title". //it Gets or sets the window title. return functionreturn title? (window.title = title): Inventory.storename +  "+ Cart.name;}} );

Reviews: After loading the module, the return value is a closure.

Simple packaging Commonjs to define modules

If you have existing code that is written in the COMMONJS module format that is difficult to refactor using the above dependency name array parameter, you might consider directly mapping these dependencies to some local variables. You can use a commonjs simple wrapper to achieve:

define(function(require, exports, module) {        var a = require(‘a‘), b = require(‘b‘); //Return the module value return function () {}; });

The wrapping method relies on Function.prototype.toString () to assign the function content to a meaningful string value, but it does not work in some devices such as PS3 and some old opera mobile browsers. Consider using the optimizer on these devices to export the dependency to an array form.

For more information, see the Commonjs notes page and the "Sugar" section of the Why AMD page.

Comments: This usage is the same as above, the first callback with Function.prototype.toString () to convert the function into a string, and then in the lexical analysis, so dependent, it is relatively low-consumption, in principle, do not consider using this method for module encapsulation.

Defining a named Module

You may see that some define () contains a module name as the first parameter:

    //Explicitly defines the "foo/title" module:    define("foo/title",        ["my/cart", "my/inventory"],        function(cart, inventory) { //Define foo/title object in here. } );

These are often generated by the optimization tool. You can also explicitly specify the module name yourself, but this makes the module less portable-that is, if you move the file to a different directory, you have to rename it. It is generally better to avoid hard coding of the modules, but to give the optimizer tools to generate them. The optimization tool needs to generate the module name to make multiple modules into a single package, speeding up to the browser's manned speed.

Reviews: The Define function has three parameters, the first ID is the module name, the format of the name is relative to the BASEURL path to remove the file format, such as BASEURL for the JS directory, a module is placed in the Js/libs/hi.js, if the name is defined as:

define(‘libs/hi‘, [‘jquery‘], function($){......});

The benefit of such a definition form is that the module is not likely to conflict because a file with the same name is not allowed in the same directory. But also therefore Require.js recommends that we do not set the module name, because the module name is set to the ' Libs/hi ', the module must be placed in the Js/libs directory Hi.js file, to move the location, the module name should be changed. As for the later use of R.js optimization generated the module name, it is another matter. So when defining a module, the first parameter is often ignored.

Jsonp Service Dependency

Jsonp is a way of service invocation in JavaScript. It simply initiates an HTTP GET request through a script tag, which is a recognized means of implementing cross-domain service invocation.

In order to use the JSON service in Requirejs, you need to specify the value of the callback parameter as "define". This means that you can consider the value of the obtained JSONP URL as a module definition.

The following is an example of a call to the JSONP API endpoint. In this example, JSONP's callback parameter is "callback", so "Callback=define" tells the API to wrap the JSON response into a "define ()":

require(["http://example.com/api/data.json?callback=define"],    function (data) { //The data object will be the API response for the //JSONP data call. console.log(data); });

This usage of JSONP should be limited to the initialization of the application. Once the JSONP service times out, other modules defined through define () may not be executed, and error handling is not very robust.

Only JSONP services that return a value type JSON object are supported, and other return types such as arrays, strings, numbers, etc. are not supported.

This feature should not be used for JSONP connections to long-polling classes-APIs that handle real-time streaming. These APIs usually do a script cleanup after receiving a response, while Requirejs can only get the JSONP URL once--the subsequent use of require () or define () to initiate a dependency on the same URL (request) will only get a cached value.

JSONP invocation errors typically occur in the form of a service timeout because simply loading a script tag typically does not get a very detailed network error message. You can override Requirejs.onerror () to get past the error. See the error Handling section for more information.

Reviews: Cross-domain scripting calls.

Loading of modules

Common module load calls are in the following form:

require(["jquery"],function($){ //todo});

The first parameter specifies the module name to load, and the second is the corresponding injection parameter.

Help documentation

Official website API Document: Http://requirejs.org/docs/api.html#define
English API document: Http://requirejs.cn/docs/api.html#define
English API document: http://makingmobile.org/docs/tools/requirejs-api-zh/#define
English Document: http://www.zfanw.com/blog/require-js.html
English Document: http://www.fanli7.net/a/bianchengyuyan/ASP/20130419/300243.html

    • Published on December 01, 2014

The collection of the article is very good, unfortunately, some still do not understand the amount ... Requirejs Advanced: Definition and loading of modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.