RequireJs notes, requirejs

Source: Internet
Author: User

RequireJs notes, requirejs

Official Website: http://www.requirejs.org/

Http://makingmobile.org/docs/tools/requirejs-api-zh/

Plug-in function: Manages JS module files, dynamically Loads files, and merges and compresses modules when the project is completed.

 

I. Basic usage:

1. for an external link file, data-main is the name of the external link file. No suffix is required:

<Script data-main = "js/main" src = "require. js"> </script>

 

2. write code directly to the page (you can set data-main as the require. config configuration file ):

Require. config ({baseUrl :'. /js', paths: {"a": "other/a", "B": "other/B", "c": "some/c ", "d": "some/d"}, waitSeconds: 150}); // dependency loading (outer layer loading first) require (["a", "c ", "d", "B"], function () {a (); c (); d (); B ();});

Ii. Syntax Summary (for detailed syntax, see the official API)

1. Reference plug-in Functions

Test. js:

define({test:function(msg) {        alert("test" + msg);    },userName: "111"});

Requirjs reference:

Require (["test"], function (a) {// a corresponds to the file a. test ("asdf") in order ");});

2. The require function is used to call internally defined functions externally. It is valid only when all files in require are loaded.

3. File dependency loading (the current plug-in depends on jquery and will be executed only after jquery is loaded)

define(['jquery'],function($){    var returnVar = {        userName: "111",        aa: function(){}    }    return returnVar;});

4. Plug-ins reference external functions

External functions:

function callE(msg){alert('e'+msg)}function callF(msg){alert('f'+msg)}

Require Configuration:

Require. config ({baseUrl :'. /js', paths: {"e": "other/e", "f": "other/f"}, config: {// The external function is assigned 'E ': {// e indicates the size of the loaded module: 'Eee ', cal: callE}, 'F': {size: 'fff', cal: callF }}, waitSeconds: 150 })

Plug-in reference:

define(function(require, exports, module){function aa(){module.config().cal('123e');}var m={aa:aa}return m;})

5. For the jsonp service, the callback parameter of JSONP is "callback", so "callback = define" tells the API to wrap the JSON response to a "define.

Require (["http://example.com/api/data.json? Callback = define "], function (data) {// data will be called as the JSONP data API response console. log (data );});

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

6. shim: Configure dependencies and export for "browser global variable injection" scripts that do not use define () to declare dependencies and Set modules.

requirejs.config({    shim: {        'jquery.colorize': {            deps: ['jquery'],            exports: 'jQuery.fn.colorize'        },        'jquery.scroll': {            deps: ['jquery'],            exports: 'jQuery.fn.scroll'        },        'backbone.layoutmanager': {            deps: ['backbone']            exports: 'Backbone.LayoutManager'        }    }});

7. paths backup error Configuration

Requirejs. config ({// to correctly check the error in IE, force define/shim export detection enforceDefine: true, paths: {jquery: ['HTTP: // ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min ', // If the CDN Load is incorrect, reload 'lib/jquery ']} from the following locations.)

8. DOM Ready

After the DOM is loaded, run the requeire code. The domReady plug-in must be loaded separately.

Require (['domainready! '], Function (doc) {// this function will be called in DOM ready. // Note 'domainready! 'Value is the current document });

9. Error capture

requirejs.onError = function (err) {    console.log(err.requireType);    if (err.requireType === 'timeout') {        console.log('modules: ' + err.requireModules);    }    throw err;};

Iii. Merge and compress the r. js Module

You must place r. js in the directory and have a configuration file for merging rules.

For example, build. js:

({AppDir :'. /', baseUrl :'. /js', dir :'. /dist ', modules: [{name: 'config' // The data-main introduced file exclude: ['other/B'] // uncompressed file} on the page }, {name: 'config2'}, {name: 'main'}], fileExclusionRegExp:/^ (r | build )\. js $/, optimizeCss: 'standard', removeCombined: true, paths: {a: 'EMPTY: ', // empty: indicates that the file is not compressed and merged, and B is requested separately: 'Other/B ', c: 'Some/C', d: 'Some/d', e: 'Other/E', f: 'Other/F '}})

R. js depends on the nodejs environment. Usage: Enter the directory where the file is located and run node r. js-o build. js.

Iv. Project instances

Project Background: VC embedded webpage project, which requires simple data interaction with VC

Code Design:

1. Independent file configuration file path, which is referenced and loaded independently before require. js

Config. js:

// Define the configuration as the global variable "require" before loading require. js, which will be automatically applied. The dependencies defined in the following example are stored in require. js. Once require () is defined, var require = {baseUrl :'. /js', paths: {"a": "other/a", "B": "other/B", "c": "some/c ", "d": "some/d"}, waitSeconds: 150}

2. Page Introduction file (code used for module files)

<Scriptdata-main = "test6" src = "require. js"> </script>

3. modules and directories by function

4. Extraction interface.

Assign a value to the VC-Defined Function in config. js through config. cal.

Functions provided to VC (mostly callback after event execution), define an initialization object in config. js, and assign values in each module, such as initialization object:
Var vcCallback = {refreshList: function () {}, // refresh list data refreshUserInfo: function () {}// refresh user data}

Rewrite the require () Code, for example, vcCallback. refreshList = createView;




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.