


Modular programming based on RequireJS and JQuery - comprehensive analysis of common problems_javascript skills
As the code logic of js is getting heavier and heavier, a js file may have thousands of lines, which is very unfavorable for development and maintenance. Recently, I am splitting the logic-heavy JS into modules. When I was struggling with whether to use requirejs or seajs, I finally preferred requirejs. After all, official documents are more professional...
However, even with complete official documentation, we still encounter many problems, such as the use of jquery-ui.
The following is a step-by-step explanation of the problems I encountered and the solutions.
Understanding of AMD and CMD
A typical example of AMD (asynchronous module definition) is requirejs, while a typical example of CMD (common module definition) is Taobao's seajs.
What they have in common is that they both load js asynchronously. But the difference is that require.js will be executed immediately after loading; while seajs will not be executed until it enters the main function and needs to be executed.
If you use seajs, the initial loading and execution efficiency will be higher, but js may be fetched and executed during use, so lags may occur and affect the user experience (I have not tried it, so if I am wrong, Don’t be surprised). And requirejs executes all loaded js at the beginning. At this time, if there are some execution methods in your module, they may not be executed in the order you want.
Therefore, if you are used to asynchronous programming and want to have complete documentation, it is recommended to use requirejs; if you want to have special requirements for the execution order and facilitate development, you can also use seajs.
How to solve the circular dependency problem in requirejs
If a module a you define uses module b, and module b uses module a, then a circular dependency exception will be thrown.
For example, I wrote an example of circular dependency here.
Main page:
<!DOCTYPE html> <html> <head> </head> <body> <script data-main="test.js" src="lib/require.js"></script> </body> </html>
Main method:
requirejs.config({ baseUrl: './' }); requirejs(['js/a'],function (a){ console.log("in test"); a.testfromb(); });
In the a.js module, the test() method provides the method of calling b, and the testfromb() method calls the method of 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(); } } });
In module b, 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 is equivalent to a calling b's method, but b's method depends on a's method, which creates a circular dependency. The browser will prompt an error:
Uncaught Error: Module name "js/a" has not been loaded yet for context: _
According to the official documentation, this is a design problem and should be avoided as much as possible. So what should you do if you can't avoid it? Module b can be modified 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(); } } });
Here is to wait until the test() method is executed before loading the a module. At this time, module a has obviously been loaded. You can see the output information:
in b a.js:3 in a test.js:6 in test a.js:9 testfromb in a b.js:6 test in b a.js:6 test in a
In the same way, it may not work if you modify a. This is because the order of module loading starts from b.
For source code of circular dependencies, please refer to the cloud disk
How to use jquery in requirejs
If you want to use jquery relatively easily, just add the corresponding dependencies directly to main.js:
requirejs.config({ baseUrl: './', paths:{ 'jquery':'lib/jquery' } }); requirejs(['jquery'], function ($){ $('#test').html('test'); });
如何在requirejs中使用jquery插件 对于jquery的插件,比较常见的做法都是传入一个jquery的对象,在这个jquery对象的基础上添加插件对应的方法。 首先需要添加jquery插件的依赖,这里用两个插件举例子——jquery-ui和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 ($){ .... });
由于jquery插件都需要依赖于jquery,因此可以在shim中指定依赖关系。 除了上面这种使用方法,也可以使用commonJS风格的调用:
define(function(require){ var $ = require('jquery'); require('jquery-ui'); require('jquery-dataTables'); //下面都是测试,可以忽略 var _test = $('#test'); _test.selectmenu({ width : 180, change : function(event, ui) { console.log('change'); } }); return { test:function(){ //测试jquery-ui _test.append($('<option>test1</option><option>test1</option>')); _test.selectmenu("refresh"); //测试jquery-datatables var _table = $('table'); _table.dataTable(); } } });
However, when executing the above code, an exception will be reported:
Uncaught TypeError: _table.dataTable is not a function
This is because dataTables is not a require-style module, so if it is introduced directly like this, its internal anonymous functions will not be executed. You can modify its anonymous function, passing in the $ object, in the last line:
*/ return $.fn.dataTable; //}));原来是这样 }($)));//这里增加执行这个匿名函数,并且传入$对象。 }(window, document));
This is also a method of searching on the Internet, but the principle is due to lack of experience....
You can refer to the cloud disk for the sample code. Since the imported resources are not complete, an error will be reported and can be ignored. Because being able to execute the UI plug-in means it has been successful.
Problems using jquery-ui with requirejs
Since requirejs will be executed immediately after loading the js file, if your jquery ui plug-in needs to refresh the DOM page, it may cause the page's events to fail.
For example, after your module is loaded, a click event is bound to a certain element $('#test') on the page. However, if a certain UI plug-in is used, the plug-in will re-render the DOM element, and the click event corresponding to test will become invalid.
Solution:
•Delay event binding until the DOM element is rendered and then manually trigger the binding;
•Event capture can also be used instead of event binding of DOM elements (too troublesome...not recommended).
For example, in the DOM reconstructed JS module, the code that executes rendering is as follows:
require("xxx").initEvents(); Common scenarios:
For example, I use the jquery-steps UI plug-in on the page, which will re-render the page. This caused the events I originally bound to become invalid... I could only postpone binding until the js page was reconstructed and then bind again.
The above article - Modular Programming Based on RequireJS and JQuery - Comprehensive Analysis of Frequently Asked Questions is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment