最近工作:封装组件

许毅
2023-12-01

最近一直在封装组件,自己的js能力也有了一定的提升,现在分享一下,封装好的组件,基于原始的组件进行封装,没有进行原组件的修改。

日期组件:my97-date

(function($) {		
	var defaults={
		dateFmt : 'yyyy-MM-dd',
		skin  : 'default',
		maxDate:'',
		minDate:'',
		disabledDays:'',
		doubleCalendar:false
	};
	var fmt=['yyyy-MM-dd','yyyy-MM-dd HH:mm:ss','yyyy-MM-dd HH','yyyy-MM-dd HH:mm'];
	var methods = {
		//默认执行方法
		init : function(options) {
			var _this = $(this);	
			var settings = $.extend(defaults, options);
			var id=_this.attr('id');
			setAttr(id,settings);
		},
		
		//只能选择未来的时间,不包括当前时间
		future : function (options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.minDate='%y-%M-{%d+1}';
			var id=_this.attr('id');
			setAttr(id,settings);	
		},
		//只能选择过去的时间,包括当前时间
		past : function(options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.maxDate='%y-%M-%d';
			var id=_this.attr('id');
			setAttr(id,settings);		
		},
		
		//只有在工作日有效
		weekable : function(options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.disabledDays=[0,6];
			var id=_this.attr('id');
			setAttr(id,settings);
		},
		
		//显示双日历
		doubleCalendar : function(options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.doubleCalendar=true;
			var id=_this.attr('id');
			setAttr(id,settings);
		},
		
		//选择开始,必须和after使用
		before : function (otherId,options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.maxDate='#F{$dp.$D(\''+otherId+'\')||\'2070-10-01\'}';
			var id=_this.attr('id');
			setAttr(id,settings);
		},
		
		//结束时间,必须和before使用
		after : function (otherId,options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.minDate='#F{$dp.$D(\''+otherId+'\')}',
			settings.maxDate='2070-10-01';
			var id=_this.attr('id');
			setAttr(id,settings);
		}
		
	};
	
	function setAttr(id,settings){
		var params=setParams(settings);
		$("#" + id).addClass('Wdate');
		$("#" + id).bind("focus", function(){
			WdatePicker(params);
		});	
		resetParams();
	}
	
	function resetParams(){
		defaults={
			dateFmt : 'yyyy-MM-dd',
			skin  : 'default',
			maxDate:'',
			minDate:'',
			disabledDays:'',
			doubleCalendar:false
		};
	}
	
	function setParams(settings){
		for ( var i = 0; i < fmt.length; i++) {
			if((settings.dateFmt)==(fmt[i])){
				return settings;
			}
		}
		settings.dateFmt='yyyy-MM-dd';
		return settings;
	}
	
	function setMax(id,otherId,settings){
		settings.minDate='#F{$dp.$D(\''+id+'\')}',
		settings.maxDate='2070-10-01';
		$("#" + otherId).addClass('Wdate');
		$("#" + otherId).bind("click", function(){
			WdatePicker(settings);
		});	
	}
	
	$.fn.datePicker = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {//如果没有制定的方法,直接使用init
			return methods.init.apply(this, arguments);
		} else {
			$.error('The method ' + method + ' does not exist in $.datePicker');
		}
	};
})(jQuery);


2.page分页封装

/**
 * 把page分页包装为jquery插件,调用插件中的方法。
 */
(function($){
	$.com.page = {
		//对分页进行初始化
		init:function(domId,settings){
			var dataUrl = $("#"+settings.formId).attr("action");
			if(!dataUrl || dataUrl.trim()=="")return false;
			var urlSplit = dataUrl.indexOf('?')==-1?"?":"&";
			var pageSettings = {type:settings.type,showSwitchSize:false,dataUrl:dataUrl,urlSplit:urlSplit};
			$.extend(pageSettings, settings);
			setCacheSetting(domId,pageSettings);
			$("#"+domId).addClass("pageBar");
			if(renders[pageSettings.type]){
				renders[pageSettings.type].init(domId,pageSettings);
			}
			return true;
		},
		//获取url链接
		goUrl:function(url){
			if(!url)return;
			window.location = url;
		},
		//去首页
		gotoFirst:function(pageBarId){
			this.gotoPage(pageBarId,1);
		},
		//去尾页
		gotoLast:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			this.gotoPage(pageBarId,settings.pageInfo.totalPages);
		},
		//上一页
		gotoPrevious:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			this.gotoPage(pageBarId,settings.pageInfo.currentPage-1);
		},
		//下一页
		gotoNext:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			this.gotoPage(pageBarId,settings.pageInfo.currentPage+1);
		},
		gotoPage:function(pageBarId,pageNo){
			var settings = getCacheSetting(pageBarId);
			var containerId = settings.containerId;
			var formId = settings.formId;
			var url = settings.dataUrl+settings.urlSplit+"page.pageSize="+settings.pageInfo.pageSize+"&page.pageNo="+pageNo;
			var params={};
			paramsStr=$("#"+formId).serializeArray();
			if(paramsStr!=""){
				$.each(paramsStr, function(i, field){
					params[field.name] = field.value;
				});
			}
			
			if(containerId!=null&&containerId!=""){
				$('#'+containerId).load(url, params);
			}else{
				this.goUrl(url);
			}
		},
		jumpPage:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			var jumpPageNo = $("#pn_"+pageBarId).val();
			if(!/^[0-9]*[1-9][0-9]*$/.test(jumpPageNo))return;
			if(jumpPageNo<1){this.gotoFirst(pageBarId);return;}
			if(jumpPageNo>settings.pageInfo.totalPages){this.gotoLast(pageBarId);;return;}
			this.gotoPage(pageBarId,jumpPageNo);
		},
		changePageSize:function(pageBarId,size){
			var settings = getCacheSetting(pageBarId);
			settings.pageInfo.pageSize = size;
			setCacheSetting(pageBarId,settings);
			this.gotoFirst(pageBarId);
		},
		getPageSize:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			if(!settings) return 0;
			return settings.pageInfo.pageSize;
		},
		getCurrentPage:function(pageBarId){
			var settings = getCacheSetting(pageBarId);
			if(!settings) return 0;
			return settings.pageInfo.currentPage;
		},
		refresh:function(pageBarId){
			this.gotoPage(pageBarId,1);
		}
	};
	
	function setCacheSetting(pageBarId,settings){
		$("#"+pageBarId).data("settings",settings);
	}
	
	function getCacheSetting(pageBarId){
		return $("#"+pageBarId).data("settings");
	}
	
	function buildNumberArray(sourceArray){
		var targetArray = [];
		var filterStr="";
		$.each(sourceArray,function(){
			var obj = parseInt(this);
			if(!isNaN(obj)&&filterStr.indexOf(""+obj)<0){
				filterStr+=obj;
				targetArray.push(obj);
			}
		});
		return targetArray;
	}
	
	var renders = {
		normal:{
			init:function(domId,settings){
				var pageBarId = domId;
				var pageInfo = settings.pageInfo;
				var pageSize = pageInfo.pageSize;
				var showSwitchSize = settings.changePageSize;
				
				var page_content = [];
				
				page_content.push('<table width="100%" cellspacing="0" cellpadding="0" border="0">');
				page_content.push('	<tbody><tr><td class="w20"> </td>');
				page_content.push('	<td align="left" nowrap="nowrap">总记录:'+pageInfo.totalRecord+'条</td>');
				if(showSwitchSize){
					var changePageDataNumberArray;
					if(settings.changePageSizeNumber && typeof(settings.changePageSizeNumber)=='string'){
						var changePageSizeNumber = buildNumberArray(settings.changePageSizeNumber.split(","));
						changePageDataNumberArray = changePageSizeNumber.length>1?changePageSizeNumber:buildNumberArray([10,20,50]);
					}else{
						changePageDataNumberArray = buildNumberArray([10,20,50]);
					}
					changePageDataNumberArray = changePageDataNumberArray.sort(function(a, b){return (a > b) ? 1 : -1});
					
					page_content.push('	<td class="w70" nowrap="nowrap">每页显示</td>');
					page_content.push('	<td class="w100" nowrap="nowrap"><ul class="pageNum">');
					$.each(changePageDataNumberArray,function(i,size){
						var sizeClass = (i==0)?"top":(i+1==changePageDataNumberArray.length)?"bottom":"center";
						page_content.push('	<li class="'+sizeClass+'"><p '+(pageSize==size?'class="select"':'')+'><a href="javascript:void(0);" οnclick="$.lw.page.changePageSize(\''+pageBarId+'\','+size+');">'+size+'</a></p></li>');
					});
					page_content.push('	</ul></td>');
				}
				page_content.push('	<td class="w20"> </td>');
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(pageInfo.isFirstPage?'<span class="gray">首页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoFirst(\''+pageBarId+'\');return false;">首页</a></td>');
				page_content.push('	</td>');
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(!pageInfo.isHavePrePage?'<span class="gray">上一页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoPrevious(\''+pageBarId+'\');return false;">上一页</a></td>');
				page_content.push('	</td>');		
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(!pageInfo.isHaveNextPage?'<span class="gray">下一页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoNext(\''+pageBarId+'\');return false;">下一页</a></td>');
				page_content.push('	</td>');		
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(pageInfo.isLastPage?'<span class="gray">尾页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoLast(\''+pageBarId+'\');return false;">尾页</a></td>');			
				page_content.push('	</td>');
				page_content.push('	<td class="w20"> </td>');
				page_content.push('	<td class="w170" nowrap="nowrap"><span style="padding-left: 6px;">当前页</span><input type="text" id="pn_'+pageBarId+'" size="2" value="'+pageInfo.currentPage+'" class="page-num" οnkeydοwn="if(event.keyCode==13){$.lw.page.jumpPage(\''+pageBarId+'\');return false;}" value="'+pageInfo.currentPage+'">');
				page_content.push('	<span style="padding-right: 6px;">/共'+pageInfo.totalPage+'页</span></td>');
				page_content.push('	<td class="w20"> </td>');
				page_content.push('	</tr></tbody></table>');		
				$("#"+pageBarId).append(page_content.join(""));
			}
		},
		simple:{
			init:function(domId,settings){
				var pageBarId = domId;
				var pageInfo = settings.pageInfo;
				var pageSize = pageInfo.pageSize;
				var showSwitchSize = settings.changePageSize;
				
				var page_content = [];
				
				page_content.push('<table width="100%" cellspacing="0" cellpadding="0" border="0">');
				page_content.push('	<tbody><tr>');
				if(showSwitchSize){
					var changePageDataNumberArray;
					if(settings.changePageSizeNumber && typeof(settings.changePageSizeNumber)=='string'){
						var changePageSizeNumber = buildNumberArray(settings.changePageSizeNumber.split(","));
						changePageDataNumberArray = changePageSizeNumber.length>1?changePageSizeNumber:buildNumberArray([10,20,50]);
					}else{
						changePageDataNumberArray = buildNumberArray([10,20,50]);
					}
					changePageDataNumberArray = changePageDataNumberArray.sort(function(a, b){return (a > b) ? 1 : -1});
					
					page_content.push('	<td class="w70" nowrap="nowrap">每页显示</td>');
					page_content.push('	<td class="w100" nowrap="nowrap"><ul class="pageNum">');
					$.each(changePageDataNumberArray,function(i,size){
						var sizeClass = (i==0)?"top":(i+1==changePageDataNumberArray.length)?"bottom":"center";
						page_content.push('	<li class="'+sizeClass+'"><p '+(pageSize==size?'class="select"':'')+'><a href="javascript:void(0);" οnclick="$.lw.page.changePageSize(\''+pageBarId+'\','+size+');">'+size+'</a></p></li>');
					});
					page_content.push('	</ul></td>');
				}
				page_content.push('	<td class="w20"> </td>');
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(!pageInfo.isHavePrePage?'<span class="gray">上一页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoPrevious(\''+pageBarId+'\');return false;">上一页</a></td>');
				page_content.push('	</td>');		
				page_content.push('	<td class="w170" nowrap="nowrap"><input type="text" id="pn_'+pageBarId+'" size="2" value="'+pageInfo.currentPage+'" class="page-num" οnkeydοwn="if(event.keyCode==13){$.lw.page.jumpPage(\''+pageBarId+'\');return false;}" value="'+pageInfo.currentPage+'">');
				page_content.push('	<span style="padding-right: 6px;">/'+pageInfo.totalPages+'</span></td>');
				page_content.push('	<td class="w70 tc" nowrap="nowrap">');
				page_content.push(!pageInfo.isHaveNextPage?'<span class="gray">下一页</span>':'<a href="javascript:void(0);" οnclick="$.lw.page.gotoNext(\''+pageBarId+'\');return false;">下一页</a></td>');
				page_content.push('	</td>');		
				page_content.push('	<td class="w20"> </td>');
				page_content.push('	</tr></tbody></table>');		
				
				$("#"+pageBarId).append(page_content.join(""));
			}
		}
	};
})(jQuery);

(function($) {		
	var defaults={
		formId  : 'form', //默认的进行分页的表单id
		pageInfo : '${page.info}',
		type : 'normal',//normal是正常分页,simple是简单分页
		changePageSize : true ,
		changePageSizeNumber :'10,30,50'
	};
	var methods = {
		//默认执行方法
		init : function(options) {
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			var id=_this.attr('id');
			$.lw.page.init(id,settings);
		},
		//不允许分页的page改变
		single : function(options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.changePageSize=false;
			var id=_this.attr('id');
			$.lw.page.init(id,settings);
		},
		simple: function(options){
			var _this = $(this);	
			var settings = $.extend(defaults,options);
			settings.type='simple';
			var id=_this.attr('id');
			$.lw.page.init(id,settings);
		}
		
	};
	
	$.fn.pageBar = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {//如果没有制定的方法,直接使用init
			return methods.init.apply(this, arguments);
		} else {
			$.error('The method ' + method + ' does not exist in $.page');
		}
	};
})(jQuery);

3.百度编辑器 ueditor的封装

/**
 * 把ueditor包装为jquery插件,调用插件中的方法。
 */
(function($) {			
	var methods = {
		//默认执行方法
		init : function(options) {
			var defaultToolbar = [
			                       'fullscreen', 'source', '|', 'undo', 'redo', '|',
			                       'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
			                       'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
			                       'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
			                       'directionalityltr', 'directionalityrtl', 'indent', '|',
			                       'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
			                       'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
			                       'simpleupload', 'insertimage', 'emotion', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
			                       'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
			                       'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
			                       'print', 'preview', 'searchreplace', 'help', 'drafts'
			                   ];
			var simpleToolbar = ['undo', 'redo','bold', 'italic', 'underline', 'strikeThrough'];
			var defaults = {
					toolbars:defaultToolbar,
					name:"",
					content:"",
					wordCount:false,
					initialFrameWidth:600,
			        initialFrameHeight:320,
					//是否采用简化模式
					simpleEnabled:false
			};
			var settings = $.extend(defaults, options);		
			settings.toolbars = settings.simpleEnabled ? simpleToolbar : defaultToolbar;
			var _this = $(this);	
			var id = _this.attr('id');
			var ue = UE.getEditor(id,settings);
			ue.ready(function() {
				ue.setContent(settings.content);
			});
			$("#"+id).data("ueditor",ue);
		},
		
		//获取文本的内容,带标签
		getContent : function(){
			var _this = $(this);
			var content = "";
			var id = _this.attr('id');
			var ue = $("#"+id).data("ueditor");
			ue.ready(function() {
				content = ue.getContent();
			});
			return content;
		},
		
		//获取纯文本内容
		getContentTxt : function(){
			var content="";
			var _this = $(this);	
			var id = _this.attr('id');
			var ue=$("#"+id).data("ueditor");
			ue.ready(function() {
				content= ue.getContentTxt();
			});
			return content;
		}
		
	};
	

	$.fn.ueditor = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {//如果没有制定的方法,直接使用init
			return methods.init.apply(this, arguments);
		} else {
			$.error('The method ' + method + ' does not exist in $.ueditor');
		}
	};
})(jQuery);



 类似资料: