企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC=1,4] ### JavaScript编码规范 #### 微擎系统中,公共引用的js文件包括 **Jquery**、**Util** 在使用以上两个Js文件时不需要require引用,使用其它Js文件需要遵循 **AMD** 的引用方式。 我们先介绍下 **AMD** ( Asynchronous Module Definition )——“**异步模块定义**”。 **require.js** 是微擎系统默认采用的 **AMD** 加载类 采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载完成之后,这个回调函数才会运行。 实现 AMD 规范的加载器其实很多,微擎系系统使用的是 require.js 。 微擎系统使用 require.js 的好处: * 实现 js 文件的异步加载,避免网页失去响应; * 管理模块之间的依赖性,便于代码的编写和维护。 >[warning] 注意系统中已经默认jquery、bootstrap、angularjs、util等js文件,无需要重复引用 ####**使用说明** ####1. require.js 加载 (已默认加载,无需手动引用) ``` <script src="js/require.js" defer async="true" ></script> ``` ####2. 模块调用 * 如果我们的代码不依赖任何其他模块,那么我们就没有必要使用 require.js . * 如果我们的代码依赖其他的模块,那么就需要requrie.js , 例如: ``` require(['jquery', 'underscore', 'util'], function ($, _, u){ // code here 主模块代码 $('#id').show(); var index = _.inArray(1, [1,2,3]); u.message('hehe'); }); ``` require.js 会先加载 jQuery、underscore 和 backbone, 然后再运行回调函数。主模块的代码就写在回调函数中。 ##### 2.1 调用自定义 js 如果调用非模块化的 js, 以**require.config** 中配置的 **baseUrl** 为基路径, 采用相对路径直到所需要的 js 文件, 一定要带后缀 **.js**. ``` < javascript addons/we7_store/template/js/amd.js> /** * 路径: addons/we7_store/template/js/amd.js */ define(['util'], function(u){ var module = {}; module.msg = function(message){ u.message(message); } return module; }); <javascript addons/we7_store/template/js/test.js> /** * 路径: addons/we7_store/template/js/test.js */ function hello(){ return 'hello world'; } ``` 注意: require 引入的 js 都需要从 "/app/resource/js/app" 开始定位到 app 转到 addons , 最后定位到模块文件夹. ``` <script> require(['../../../addons/we7_store/template/js/amd.js', // 输出变量 amd (1) '../../../addons/we7_store/template/js/test.js'] // 非标准 js, 无需设置输出参数. , function(amd){ // 输出变量(1) amd.msg(hello()); } ); </script> ``` 非模块化 js, 在 require 的回调函数中无需设置参数 ####3. 模块加载 require.js 在 js 目录下,其他标准库置于 js目录下 lib 文件夹中,自定义模块置于 app 文件夹中。 按微擎系统的js目录结构。使用 require.config() 方法,我们可以对模块的加载行为进行定义。可以将 require.config() 方法置于模块文件头部,或抽离单独的 js文件(config.js)。 ``` require.config({ paths: { "jquery": "lib/jquery.min", "underscore": " lib/underscore.min" } }); ``` 或使用 baseUrl 来改变基路径 ```` require.config({ // 设置为自定义模块路径。 baseUrl: " resource/js/app", // require.js要求,每个模块是一个单独的js文件。 paths: { // '模块名称': '相对 baseUrl 的路径 ' 'jquery': '../lib/jquery-1.11.1.min', 'underscore': '../lib/underscore-min', } }); ``` ####4. 加载非规范模块#### ``` require.config({     shim: { 'colorpicker': { //(输出的变量名),表明这个模块外部调用时的名称; exports: '$', // 依赖项, css! 依赖外部css deps: ['css!../../components/colorpicker/spectrum.css'] }, } }); ``` ####5. 加载插件 require.js 还提供一系列插件,实现一些特定的功能。 domready 插件,可以让回调函数在页面 DOM 结构加载完成后再运行。 ``` require(['domready!'], function (doc){ called once the DOM is ready }); ``` ####6. 定义模块 ``` define(['jquery', 'underscore'], function($, _ ){ var mod = {}; // code-segment return mod; }); ``` 参数: ['jquery', 'underscore'] 数组的元素是 require.config() 中声明的模块名,回调函数中会使用. '$' 为 'jquery' 模块的输出变量, '_' 为 'underscroe'模块的输出变量, $, _ 可以在回调function 中直接使用。