比较通用的模块开发(requirejs)
对于前端的模块化开发理解的还不够深入,原来写的通用的模块开发有问题,现在把相对成熟一些模板记录下来
先定义一下前提:我们有这样一个js的toolkit包,包里面有几个比较基础的功能模块,分别是events,uuid,control,其中events、uuid是功能独立的,control依赖于events和uuid。
文件夹结构:
toolkit
events.js
uuid.js
control.js
各个js的实现:
events:
(function(factory){ if (typeof define === "function" && define.amd) { //dom amd、requirejs define(factory); } else if (typeof module === "object" && typeof module.exports === "object") { //node module.exports = factory(require); } else { //window this["events"] = factory(this); } }(function(require){ function events(){ } events.prototype.on=function(){ } events.prototype.emit=function(){ } return events }))
uuid:
(function(factory){ if (typeof define === "function" && define.amd) { //dom amd、requirejs define(factory); } else if (typeof module === "object" && typeof module.exports === "object") { //node module.exports = factory(require); } else { //window this["uuid"] = factory(this); } }(function(require){ function uuid(){ } uuid.v1=function(){ } uuid.v2=function(){ } uuid.v4=function(){ } return uuid }))
control:
(function(factory){ if (typeof define === "function" && define.amd) { //dom amd、requirejs define(factory); } else if (typeof module === "object" && typeof module.exports === "object") { //node module.exports = factory(require); } else { //window this["control"] = factory(this); } }(function(require){ var events,uuid,jquery;//jquery作为引用第三方的一个示例 if(typeof require ==="function"){ events=require("./events"); uuid=require("./uuid"); jquery=require("jquery"); }else{ events=require["events"]; uuid=require["uuid"]; jquery=require["$"]; } function control(){ events.call(this); } control.prototype=jquery.extend(control.prototype,events.prototype); control.prototype.show=function(){ this.emit("show",this,{}); } control.prototype.hide=function(){ this.emit("hide",this,{}); } return uuid }))
在html中进行引用时分为两种方式:
1.直接通过script的方式进行引用:
<script src="events"></script> <script src="uuid"></script> <script src="control"></script>
2.通过requirejs的包方式进行引用:
require.config({ packages:[{ name:"toolkit",//包名称 location:"toolkit"//包的地址(baseurl) }] }); require(["toolkit/control"],function(){ //code })
按照上面的示例,根据实际的需求进行包开发,按照两种方式进行js的引用,对于不涉及到dom操作的功能同时也可以在nodejs中使用。