Home > Web Front-end > JS Tutorial > Analysis of daily problems in modular programming based on RequireJS and JQuery_javascript skills

Analysis of daily problems in modular programming based on RequireJS and JQuery_javascript skills

WBOY
Release: 2016-05-16 15:05:41
Original
1318 people have browsed it

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 all 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). 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, 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>
Copy after login

Main method:

requirejs.config({
baseUrl: './'
});
requirejs(['js/a'],function (a){
console.log("in test");
a.testfromb();
});
Copy after login

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();
}
}
});
Copy after login

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();
}
}
});
Copy after login

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: _ 
Copy after login

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();
}
}
});
Copy after login

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
Copy after login

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');
});
Copy after login

How to use jquery plugin in requirejs

For jquery plug-ins, a common approach is to pass in a jquery object and add the corresponding methods of the plug-in based on this jquery object.

First you need to add the dependencies of the jquery plug-in. Here are two plug-ins as examples - 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 ($){
....
});
Copy after login

Since jquery plug-ins all need to depend on jquery, the dependency can be specified in the shim.

In addition to the above usage method, you can also use commonJS style calling:

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();
}
}
});
Copy after login

However, when executing the above code, an exception will be reported:

Uncaught TypeError: _table.dataTable is not a function 
Copy after login

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));
Copy after login

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, this 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 is the entire description of the editor’s analysis of daily problems in modular programming with RequireJS and JQuery. I hope it will be helpful to everyone!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template