Modular programming based on Requirejs and jquery--a comprehensive analysis of common problems _javascript skills

Source: Internet
Author: User

Because the code of JS more and more heavy, a JS file may have thousands of lines, very detrimental to the development and maintenance. Recently, the logic is very heavy JS split into modules, in a tangle is the use of Requirejs or SEAJS, the end is biased towards the requirejs. After all, official documents are more professional ...

However, even with the full official document, there are still many problems, such as the use of Jquery-ui.

Here is a step-by-step explanation of the problems I encountered, as well as the solution.

Understanding of AMD and CMD

AMD (Asynchronous module definition) is typical of Requirejs, and cmd (Common module definition) is typical of Taobao Seajs.

Their common point is that they will load JS asynchronously. However, the difference is that Require.js is executed immediately after loading, and SEAJS is not executed until the main function needs to be executed.

If you use SEAJS initial load execution efficiency will be relatively high, but in the process of use may take the execution JS, so may appear cotton, affect the user experience (since I have not tried, if wrong, don't mind). And Requirejs in the beginning of all the loaded JS is executed, at this time, if your module has some implementation methods, they may not be in the order you want to execute.

Therefore, if you are accustomed to asynchronous programming, and you want to have good documentation recommended to use REQUIREJS, and if you want to have special requirements for the order of execution and facilitate development, you can also use SEAJS.

How to solve the problem of cyclic dependencies in Requirejs

If one of your defined a modules uses the B module, and the B module uses the A module, it throws the loop-dependent exception.

For example, I write a circular dependency example here.

Main Page:

<! DOCTYPE html>
 
 

Main method:

Requirejs.config ({
  baseurl: './'
});

Requirejs ([' js/a '],function (a) {
  console.log ("in Test");
  A.testfromb ();
});

In the A.js module, the Atest () method provides a method for B invocation, Testfromb () method to call B

Define (function (require) {
  var b = require ("js/b");
  Console.log ("in a");
  return {
    atest:function () {
      console.log (' Test in a ');
    },
    testfromb:function () {
      Console.log ("Testfromb in a");
      B.btest ();}}
);

b module, the method of a is called.

Define (function (require) {
  var a = require ("js/a");
  Console.log ("in B");
  return {
    btest:function () {
      console.log ("Test in B");
      A.atest ();}}
);

This equates to a method called B, but the B method relies on the method of a, which creates a circular dependency. The browser prompts for an error:

uncaught error:module Name "js/a" has not been loaded to context: _

According to the official document, this is a design problem that should be avoided as far as possible. So what if we can't avoid it? You can modify the B module like this:

Define (function (require) {
  //var a = require ("js/a");
  Console.log ("in B");
  return {
    btest:function () {
      console.log ("Test in B");
      Require ("js/a"). Atest ();

This is when the A module is loaded until the Atest () method is executed. At this point, a module is obviously loaded. You can see the output information:

In the B
a.js:3 in a
test.js:6 with test
a.js:9 Testfromb in a
b.js:6 test into B
a.js:6 test in a

In the same way, modifying a may be bad. This is because the order in which the modules are loaded starts with B.

The source of the circular dependency can refer to the cloud disk

How to use jquery in Requirejs

If you want to use jquery more simply, add the corresponding dependencies directly in the Main.js:

Requirejs.config ({
  baseurl: './',
  paths:{
    ' jquery ': ' Lib/jquery '
  }
});

Requirejs ([' jquery '],
function ($) {
  $ (' #test '). html (' Test ');
};
How to use the jquery plugin in Requirejs

for jquery plug-ins, it's more common to pass in a jquery object, adding a plug-in approach based on this jquery object.

First you need to add the jquery plug-in dependencies, here are two plug-ins for example--jquery-ui and Jquery-datatables
Requirejs.config ({
  baseurl: './',
  paths:{
    ' jquery ': ' Lib/jquery ',
    ' jquery-ui ': ' lib/ Jquery-ui ',
    ' jquery-datatables ': ' Lib/jquery.datatables '
  },
  shim:{
    ' jquery-ui ': [' jquery '],
    ' jquery-datatables ': [' jquery ']
  }
};

Requirejs ([' jquery ', ' jquery-ui ', ' jquery-datatables '],
function ($) {
  ...
});
Because jquery plug-ins need to rely on jquery, you can specify dependencies in shim.
In addition to this use, you can use the Commonjs style call:

Define (function (require) {
  var $ = require (' jquery ');
  Require (' Jquery-ui ');
  Require (' jquery-datatables ');
  
    Below are the tests that can ignore
  var _test = $ (' #test ');
  _test.selectmenu ({
    width:180,
    change:function (event, UI) {
      console.log (' change ');
    }
  ); Return
  {
    test:function () {
      //test Jquery-ui
      _test.append (' <option>test1</option> <option>test1</option> '));
      _test.selectmenu ("refresh");
      Test Jquery-datatables
      var _table = $ (' table ');
      _table.datatable ();}}
);

However, executing the above code will report an exception:

Uncaught TypeError: _table.datatable is not a function

This is because DataTables is not a require-style module, so it is introduced directly and does not execute its internal anonymous functions. You can modify its anonymous function, passing in the $ object, on the last line:

* * return

  $.fn.datatable;
});
//This adds this anonymous function and passes in the $ object.

} (window, document));

This is also the way to search the Internet, the principle of the lack of experience ....

Sample code can refer to the cloud disk, because the introduction of the resource is not very full, so it will be an error, can be directly ignored, because the implementation of the UI plugin is said to have been successful.

The problem of Requirejs using Jquery-ui

Because Requirejs loads the JS file and executes immediately, if your jquery UI plugin needs to refresh the DOM page, it may cause the page event to fail.

For example, when your module is loaded, the Click event is bound to an element of the page $ (' #test '). However, using a UI plug-in, the plugin will render the DOM element again, and test the corresponding click event will fail.

Solution:

• Delay the event binding until the DOM element is rendered and then manually trigger the binding;
• You can also use event capture to replace event bindings for DOM elements (too cumbersome ...). Not recommended).

For example, in the DOM refactoring JS module, execute the render code below:

Require ("XXX"). initevents (); Common scenarios:

For example, I use the Jquery-steps UI plugin on the page, which will render the page again. This causes my first binding event to fail .... Only postpone to this JS refactor the page, and then bind the line.

The above is based on REQUIREJS and jquery Modular Programming-FAQ is a comprehensive analysis of the small series to share all the content, I hope to give you a reference, but also hope that we support the cloud habitat community.

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.