Ext封装(二)

/**
 *@projectname Student's Flat Manager
 *@author 
 *@filename ext-package.js
 *@today 2009-09-17 
 */
 Ext.namespace('Ext.ux');
  Ext.QuickTips.init();  //按钮快捷提示初始化
  Ext.form.Field.prototype.msgTarget = 'qtip';

 /**
  * 
  *messagebox show 
  */
Msg = Ext.MessageBox;
Ext.RoleInfo = function(){};
Ext.roleInfo = parent.window.Ext.roleInfo ? parent.window.Ext.roleInfo : new Ext.RoleInfo();
 /**
  *IP访问验证  
  */
 Ext.ux.lock=function(t){
    var requestURL = t==null?document.URL:parent.document.URL;
    var ip="127.0.0.1:8080";
    var flag = true;
    var validURL="http://"+ip+"/sfm/sfmindex.jsp/";
    if(validURL.indexOf(requestURL)!=0){
       window.location.href="http://"+ip+"/sfm/";
       flag = false;
    }
    return flag;
 };
 
 /**
  *封装 suggest显示 
  */
 Ext.ux.suggest = function(){
    var msgCt;

    function createBox(t, s){
        return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3><font color=#FF0000>', t, '</font></h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
            }
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
            m.slideIn('t').pause(2).ghost("t", {remove:true});
        },

        init : function(){
            /*
            var t = Ext.get('exttheme');
            if(!t){ // run locally?
                return;
            }
            var theme = Cookies.get('exttheme') || 'aero';
            if(theme){
                t.dom.value = theme;
                Ext.getBody().addClass('x-'+theme);
            }
            t.on('change', function(){
                Cookies.set('exttheme', t.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });*/

            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    }
}();

Ext.apply(Ext.MessageBox,{
      suggest:Ext.ux.suggest.msg
});
/**
 *iframe 
 */
Ext.ux.IFrameComponent = Ext.extend(Ext.BoxComponent, {
			     onRender : function(ct, position){
			          this.el = ct.createChild({tag: 'iframe', id: this.id, frameBorder: 0, src: this.URL});
			     }
             });

 /**
  * Cookies
  */
var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};

Ext.main = {
	addItems : function(items){
		var tabpanel=new Ext.TabPanel({
								activeTab: 0,
								border:false,
								items:items
							}); 
		var viewport = new Ext.Viewport({
							layout:"fit",
							border:false,
							items: [tabpanel],
							listeners:{
							   render:function(){
							        Ext.get('loading').remove();
							   }
							}
						});		
		return tabpanel;				
	},
	maximize : function(){
		parent.window.index.menuLayout.collapse();	
	},
	minimize : function(){
		parent.window.index.menuLayout.expand();	
	}
}


Ext.data.DWRProxy = function(dwrCall, pagingAndSort){
  Ext.data.DWRProxy.superclass.constructor.call(this);
  this.dwrCall = dwrCall;
  //this.args = args;
	this.pagingAndSort = (pagingAndSort!=undefined ? pagingAndSort : true);
};

Ext.extend(Ext.data.DWRProxy, Ext.data.DataProxy, {
  load : function(params, reader, callback, scope, arg) {
    if(this.fireEvent("beforeload", this, params) !== false) {
//      var sort;
//      if(params.sort && params.dir) sort = params.sort + ' ' + params.dir;
//      else sort = '';
      var delegate = this.loadResponse.createDelegate(this, [reader, callback, scope, arg], 1);
      var callParams = new Array();
//      if(arg.arg) {
//        callParams = arg.arg.slice();
//			}
			
//		if(this.pagingAndSort) {
//	      	callParams.push(params.start);
//	      	callParams.push(params.limit);
//	      	callParams.push(sort);
//			}
//		callParams.push(params.queryparams);
//		callParams.push(params.sqlpath);
        Ext.apply(arg.params,params);//arg.params 是系统load时所传参数, params是自定义参数
		callParams.push(arg.params);
      callParams.push(delegate);
      this.dwrCall.apply(this, callParams);
    } else {
      callback.call(scope || this, null, arg, false);
    }
  },

  loadResponse : function(listRange, reader, callback, scope, arg) {
    var result;
    try {
      result = reader.read(listRange);
    } catch(e) {
      this.fireEvent("loadexception", this, null, response, e);
      callback.call(scope, null, arg, false);
      return;
    }
    callback.call(scope, result, arg, true);
  },

  update : function(dataSet){},

  updateResponse : function(dataSet)
  {}
});

Ext.data.ListRangeReader = function(meta, recordType){
    Ext.data.ListRangeReader.superclass.constructor.call(this, meta, recordType);
    this.recordType = recordType;
};
Ext.extend(Ext.data.ListRangeReader, Ext.data.DataReader, {
  getJsonAccessor: function(){
      var re = /[\[\.]/;
      return function(expr) {
          try {
              return(re.test(expr))
                  ? new Function("obj", "return obj." + expr)
                  : function(obj){
                      return obj[expr];
                  };
          } catch(e){}
          return Ext.emptyFn;
      };
  }(),
	
	read : function(o){
		var recordType = this.recordType, fields = recordType.prototype.fields;

		//Generate extraction functions for the totalProperty, the root, the id, and for each field
		if (!this.ef) {
			if(this.meta.totalProperty) {
				this.getTotal = this.getJsonAccessor(this.meta.totalProperty);
			}
		
			if(this.meta.successProperty) {
				this.getSuccess = this.getJsonAccessor(this.meta.successProperty);
			}

			if (this.meta.id) {
				var g = this.getJsonAccessor(this.meta.id);
				this.getId = function(rec) {
					var r = g(rec);
					return (r === undefined || r === "") ? null : r;
				};
			} else {
				this.getId = function(){return null;};
			}
			this.ef = [];
			for(var i = 0; i < fields.length; i++){
				f = fields.items[i];
				var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
				this.ef[i] = this.getJsonAccessor(map);
			}
		}

   	var records = [];
   	var root = o.data, c = root.length, totalRecords = c, success = true;

   	if(this.meta.totalProperty){
	    var v = parseInt(this.getTotal(o), 10);
			if(!isNaN(v)){
				totalRecords = v;
			}
		}

		if(this.meta.successProperty){
			var v = this.getSuccess(o);
			if(v === false || v === 'false'){
				success = false;
			}
		}

		for(var i = 0; i < c; i++){
	    var n = root[i];
      var values = {};
      var id = this.getId(n);
      for(var j = 0; j < fields.length; j++){
				f = fields.items[j];
        var v = this.ef[j](n);						
        values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
      }
      var record = new recordType(values, id);
      records[i] = record;
    }

    return {
       success : success,
       records : records,
       totalRecords : totalRecords
    };
  }
});

/**
 *Ext.ux.DwrStore 
 */
Ext.ux.DwrStore = function(method,cfg,uxcfg) {
	var config = {};
	var reader;
	if(uxcfg && uxcfg.headers){
		var recordType = Ext.data.Record.create(uxcfg.headers);
		var schema = {id: uxcfg.recordId||'idno',totalProperty: 'totalSize'};		
		reader = new Ext.data.ListRangeReader(schema,recordType);	
	}
	
	Ext.apply(config, {
		proxy: new Ext.data.DWRProxy(method, true),
		reader: reader,
		baseParams: cfg,
		remoteSort: (uxcfg && typeof uxcfg.remoteSort=='boolean') ? uxcfg.remoteSort:(cfg.paging ? true : false)
	});
	// call the superclass's constructor 
	Ext.ux.DwrStore.superclass.constructor.call(this, config);
};
Ext.extend(Ext.ux.DwrStore,Ext.data.Store);

/**
 *gridpanel封装  Ext.ux.gridPanel 
 */
Ext.ux.gridPanel=function(cfg){
   var cols = cfg.cols;
   var sqlpath = cfg.sqlpath;
   var paging = cfg.paging;
   var pageSize = cfg.pageSize;
   var method = cfg.method||DataSource.getGridData;
   var headers = new Array();
   var newcols=[];
   var uxConfig = {},pcfg = {};
   cfg.plugins=[];
   
   for(var i=0;i<cols.length;i++){
      var obj = {name:cols[i].dataIndex,mapping:cols[i].dataIndex};
      if(cols[i].type){
        obj.type=cols[i].type;
      }
      headers[headers.length]=obj;
   }
   uxConfig.headers = headers;
   uxConfig.remoteSort = cfg.remoteSort||cfg.paging;
   pcfg.sqlpath=sqlpath;
   pcfg.paging = paging;
   
   cfg.store = new Ext.ux.DwrStore(method,pcfg,uxConfig);
   if(cfg.rowNum){
   	var rowcfg=(typeof cfg.rowNum == "boolean") ? {} : cfg.rowNum;
     newcols.push(new Ext.grid.RowNumberer(rowcfg));  
   }
   if(cfg.checkBox){
   	var boxcfg = (typeof cfg.checkBox== 'boolean')?{}:cfg.checkBox;
     newcols.push((cfg.sm = new Ext.grid.CheckboxSelectionModel(boxcfg)));
   }
   for(var i=0;i<cols.length;i++){
      newcols[newcols.length]=cols[i];
   }
   cfg.colModel = new Ext.grid.ColumnModel(newcols);
   if(paging){
   var pagingbar = new Ext.PagingToolbar({
         store:cfg.store,
         pageSize:pageSize,
         displayInfo: true
    })
    cfg.bbar=pagingbar;
   }
   if(cfg.searchConfig){
      cfg.plugins.push(new Ext.ux.Search(cfg.searchConfig));	
   }
   if(cfg.summaryConfig){
      cfg.plugins.push(new Ext.ux.grid.GridSummary(cfg.summaryConfig));
   }
   Ext.ux.gridPanel.superclass.constructor.call(this, cfg);
}
Ext.extend(Ext.ux.gridPanel,Ext.grid.GridPanel,{
    load:function(params){
       if(params){
          if(typeof params=='string'){
             this.store.baseParams.queryparams=[params,'String'];
          }else if(Ext.isArray(params)){
             this.store.baseParams.queryparams=params;
          }else if(typeof params=='Object'){//sql加载查询   尚未处理
             Ext.apply(this.store.baseParams,params);
          }
       }
       if(this.paging){
        this.store.load({params:{start:0,limit:this.pageSize}});
       }else{
         this.store.load();
       }
    },
    getSelectedRows:function(cfg){
    	cfg = cfg||{};
        Ext.applyIf(cfg,{
           multiSelect:false,
           alertType:'suggest',
           err1:'请选择您所要操作的记录行',
           err2:'一次只能操作一条记录'
        });
        if(this.selModel.hasSelection()){
           var selectedNum = this.selModel.getCount();
           if(!cfg.multiSelect&&selectedNum>1){
             cfg.alertType=='suggest'?Msg.suggest('提示',cfg.err2):Msg.alert('提示',cfg.err2);
           }else{
           	 if(cfg.multiSelect){
           	      return this.selModel.getSelections();
           	 }else{
           	      return this.selModel.getSelected();
           	 }
           }
        }else{
           cfg.alertType=='suggest'?Msg.suggest('提示',cfg.err1):Msg.alert('提示',cfg.err1);
        }
    },
    getIdsFromSelectedRows:function(cfg){
    	cfg.multiSelect=cfg.multiSelect||true;
        var rs = this.getSelectedRows(cfg);
        if(rs){
        	var ids = [];
        	if(cfg.multiSelect){
           for(var i=0;i<rs.length;i++){
              ids[ids.length]=rs[i].data[cfg.id];
           }
         }else{
             ids[0]=rs.data[cfg.id];
         }
           return ids;
        }
    }
});

/**
 *Ext.ux.simpleCombo  封装
 * 
 */
Ext.ux.SimpleComboBox = function(cfg) {
	Ext.applyIf(cfg,{mode:'local'});//设置默认值
	if(cfg.sqlpath) cfg.mode='remote';
	if(cfg.data) cfg.mode='local';
	
	if(!cfg.sqlpath && cfg.mode=='remote')  {
		alert(cfg.name+'请设置sqlpath属性!');
		return;
	}
	if(cfg.mode=='local')  {
		if(!cfg.data || typeof cfg.data == "string"){
			cfg.data = Ext.ux.LocalData.get(cfg.data||cfg.name);
			if (!cfg.data) {
				alert(cfg.name+',请配置本地数据源数组!');
				return ;
			}
		}
	}	
	
    cfg.store = this.getMyStore(cfg);
	cfg.queryParam='queryValue';
	//cfg.emptyText= cfg.emptyText||'请选择';
	cfg.triggerAction= 'all';
	cfg.valueField='value';
	cfg.displayField='text';
	if(cfg.hideTrigger) cfg.readOnly=true;
	if(cfg.pageSize) cfg.minListWidth=250;
	
	if(cfg.mode=='local' && !cfg.value){
		cfg.value=cfg.store.getAt(0).data[cfg.valueField];//设置本地数据默认值
	}
	
	delete cfg.sqlpath;
	delete cfg.data;
	// call the superclass's constructor 
	Ext.ux.SimpleComboBox.superclass.constructor.call(this, cfg);
};

Ext.extend(Ext.ux.SimpleComboBox, Ext.form.ComboBox, {
	getMyStore: function(cfg){
		var store,uxConfig={headers:['value', 'text']};
		if(cfg.mode=='remote'){
			var method=DataSource.getComboData;
			var paging = cfg.pageSize ? (cfg.pageSize>0 ? true : false) :false;
			var config={
				paging:paging,sqlpath:cfg.sqlpath
			};
			if(cfg.headers){
				if(Ext.isArray(cfg.headers)){
				    for(var i=0;i<cfg.headers.length;i++){
				        uxConfig.headers[uxConfig.headers.length]=cfg.headers[i];
				    }
				}else{
				    uxConfig.headers[uxConfig.headers.length]=cfg.headers;
				}
			}
			store = new Ext.ux.DwrStore(method,config,uxConfig);				
		}else{
			store = new Ext.data.ArrayStore({
		        fields: ['value', 'text'],
		        data : cfg.data
		    });			
		}
		return store;
	}
})
Ext.reg('simplecombo',Ext.ux.SimpleComboBox);

/**
 * 前台表单数据的封装,自动将一个表单中的数据封装成一个js对象obj {}
 * 说明:
 * 1、对单选按钮radio,值为选中的按钮的inputValue,若inputValue为空,则默认为boxLabel
 * 2、对组合框combo,值为选中的值
 * 3、对复选框checkbox,值为选中的框的inputValue,若inputValue为空,则默认为boxLabel,多项以","分隔组成字符串
 * @param 表单对象
 */
Ext.ux.form = {
	getObjFromForm : function(form) {

		fields = form.getForm().items;
		var obj = {};
		var flag = true;// 特殊标记
		var checkboxValue = [];//保存复选框中的值
		var checkBoxName;//复选框对应字段名称

		for (var i = 0; i < fields.length; i++) {
			// 对应一个表单字段
			var field = fields.itemAt(i);
			var value = field.getValue();// 字段值
			var xtype = field.getXType();// 表单域类型

			if (xtype == 'radio') {// 单选处理
				if (flag) {
					if (value) {
						value = field.inputValue||field.boxLabel;
						flag = false;
						obj[field.name] = value;
					}
				}

			} else if (xtype == 'combo') {
				var index = field.store.find(field.valueField, value);// 根据属性名和值查找记录的位置
				if (index != -1) {
					var selItem = field.store.getAt(index);
					value = selItem.get(field.valueField);
					obj[field.name] = value;
				}
			} else if(xtype == 'checkbox'){
				if(value){//若选中
					checkBoxName = field.name;
					checkboxValue.push(field.inputValue||field.boxLabel)
				}
			}else{//其他类型
				obj[field.name] = value;
			}
		}
		obj[checkBoxName] = checkboxValue;

		return obj;
	}
};

你可能感兴趣的:(jsp,prototype,ext,F#,J#)