All Downloads are FREE. Search and download functionalities are using the official Maven repository.

static.scripts.beangle.beangle.js Maven / Gradle / Ivy

There is a newer version: 3.5.3
Show newest version
/**
 * Beangle, Agile Java/Scala Development Scaffold and Toolkit
 *
 * Copyright (c) 2005-2013, Beangle Software.
 *
 * Beangle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Beangle is distributed in the hope that it will be useful.
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Beangle.  If not, see .
 */
 /**
  * Version 3.3.4
  */
(function( window, undefined ) {
  if(beangle) return;
  var beangle=function (){
    return true;
  };

  /** extend function */
  beangle.extend= function(map){
    for(attr in map){
      var attrs=attr.split("."),obj=beangle,i;
      for(i=0 ;ibg.history.maxStates)History.reset();
                }
            });
        });
    },

    Go : function(url,target){
      jQuery.ajax({
        url: url,cache:false,
        type: "GET",dataType: "html",
        complete: function( jqXHR) {
          target="#"+target;
          if(jQuery(target).html().length>0){
            bg.history.snapshot();
            History.pushState({content:jqXHR.responseText,container:target},"",url);
          }else{
            var state=History.getState();
            History.replaceState({content:jqXHR.responseText,container:target,updatedAt:(new Date()).getTime()},state.title,state.url);
            try{
              jQuery(target).html(jqXHR.responseText);
            }catch(e){alert(e)}
          }
          beangle.hideAjaxMessage();
        },
        beforeSend: beangle.displayAjaxMessage
      });
    },
    snapshot:function(){
      var state = History.getState();
      if(state.data.content){
        var _t = [];
        jQuery(state.data.container +' .box:checked').each(function(index, e) {_t[_t.length] = e.value;});
        state.data.boxes=_t;
        state.updatedAt=(new Date()).getTime();
        if(_t.length>0) History.replaceState(state.data,state.title,state.url);
      }
    },
    applyState:function(state){
      if(state.data.boxes){
        jQuery(state.data.boxes).each(function(index, value) {
          jQuery(state.data.container +' .box[value=' + value + ']').prop('checked', true);
        });
      }
    },
    submit : function(form,action,target){
        if(jQuery.type(form)=="string" && form.indexOf("#")!=0){
          form = "#" + form;
        }
        if(jQuery.type(target)=="string" && target.indexOf("#")!=0){
          target = "#" + target;
        }
        bg.displayAjaxMessage();

        jQuery(form).ajaxForm({
          success:function(result)  {
            bg.history.snapshot();
            History.pushState({content:result,container:target},"",action);
            bg.hideAjaxMessage();
            return false;},
          error:function (response)  {
            try{jQuery(target).html(response.responseText);}catch(e){alert(e)}
            bg.hideAjaxMessage();
            return false;},
          url:action
       });
       jQuery(form).submit();
    }
  };

  //Go and ajax---------------------------------
  beangle.extend({
    //jump to href or anchor
    Go : function (obj,target){
      var url=obj;
      if(typeof obj =="object" && obj.tagName.toLowerCase()=="a"){
        url=obj.href;
        if(!target){
          target=bg.findTarget(obj);
        }
      }
      if(!target) target="_self";
      if("_self"==target){ self.location=url;}
      else if("_parent"==target){self.parent.location=url;}
      else if("_top" ==target){self.top.location=url;}
      else if("_new" ==target || "_blank" ==target  ){window.open(url);}
      else{
        if(!bg.isAjaxTarget(target)){
          //FIXME _blank,_top
          document.getElementById(target).src=url;
        }else{
          if(beangle.ajaxhistory){
            beangle.history.Go(url,target);
          }else {
            //using post ,hack ie8 get cache
            jQuery('#'+target).load(url,{});
          }
        }
      }
      return false;
    },
    getContextPath : function (){
      if(null===beangle.contextPath){
        if(App.contextPath){
          beangle.contextPath = App.contextPath;
        }else{
          beangle.contextPath = self.location.pathname.substring(0,self.location.pathname.substring(1).indexOf('/')+1)
        }
      }
      return beangle.contextPath;
    },
    ready:function (fn){
        jQuery(document).ready(fn);
    },
    isAjaxTarget : function (target){
      if(!target) return false;
      if(target==""||target=="_new"||target=="_blank"||target=="_self"||target=="_parent"||target=="_top"){
        return false;
      }
      targetEle=document.getElementById(target);
      if(!targetEle) return false;
      tagName=targetEle.tagName.toLowerCase();
      if(tagName=="iframe" || tagName=="object"){
        return false;
      }
      return true;
    },
    normalTarget : function(target){
      if(target==""||target=="new"||target=="_blank"||target=="_self"||target=="_parent"){
        return target;
      }
      var targetObj = document.getElementById(target);
      if(!targetObj || targetObj.tagName.toLowerCase()!="iframe") return "_self";
      else return target;
    },
    findTarget : function(ele){
      var p = ele.parentNode,finalTarget = "_self";
      while(p){
        //FIXME ui-tabs-panel
        if(p.id && p.className  && (p.className.indexOf("ajax_container")>-1 )){//||p.className.indexOf("ui-tabs-panel")>-1
          finalTarget = p.id;
          break;
        }else{
          if(p==p.parentNode) p=null;
          else p=p.parentNode;
        }
      }
      ele.target=finalTarget;
      return finalTarget;
    }
  });

  // Assert------------------------
  beangle.extend({
    assert:{
      notNull : function(object,message){
        if(null==object)  alert(message);
      }
    }
  });
  bg.extend({
    randomInt:function(){
      var num=Math.random()*10000000;
      num -= num%1;
      return num;
    }
  });
  // Logger----------------------------
  beangle.extend({
    logger:{
      // debug=0;info=1;warn=2;error=3;fatal=4;disabled=5
      level : 1,
      debug : function(message){
        if(beangle.logger.level<=0){
          var msg = '[beangle] ' + message;
          if (window.console && window.console.log) {
            window.console.log(message);
          }else if (window.opera && window.opera.postError) {
            window.opera.postError(msg);
          }else{
            alert(msg);
          }
        }
      }
    }
  });

  // Event--------------------------------------------------
  beangle.extend({
    event:{
      portable: function (e){
        if(!e) return window.event;
        else return e;
      },
      /**获得事件背后的元素*/
      getTarget: function (e){
        e=bg.event.portable(e);
        return e.target || e.srcElement;
      }
    }
  });

  // Input----------------------------------------------------
  beangle.extend({
    input:{
      toggleCheckBox : function (chk,event){
        bg.input.boxAction(chk, "toggle",event);
      },
      /**
       * 返回单选列表中选择的值
       * @return 没有选中时,返回""
       */
      getRadioValue : function (radioName){
        return bg.input.boxAction(document.getElementsByName(radioName), "value");
      },

      /**
       * 返回多选列表中选择的值
       * @return 多个值以,相隔.没有选中时,返回""
       */
      getCheckBoxValues : function (chkname){
        var tmpIds= bg.input.boxAction(document.getElementsByName(chkname), "value");
        if(tmpIds==null)return "";
        else return tmpIds;
      },
      /**
       * modify by chaostone 2006-8-2
       * 将反选取消,改为全选或者全部取消
       */
      boxAction : function (box, action,event){
        var val = "",srcElement,i;
        if (box){
          if (! box[0]){
            if (action == "selected"){
              return box.checked;
            } else if (action == "value"){
              if (box.checked)
                val = box.value;
            } else if (action == "toggle"){
              srcElement = beangle.event.getTarget(event);
              box.checked = srcElement.checked;
              if(typeof box.onchange =="function"){
                box.onchange();
              }
            }
          } else{
            for (i=0; i0) &&  totalHeight> myHeight){
            targWin.style.height = totalHeight+"px";
            bg.logger.debug('adapt frame:'+targObj.name+" height "+targWin.style.height);
          }
        }
        bg.iframe.adapt(targObj.parent);
      }
    }
  });
  //About From
  beangle.extend({
    form:{
      submit : function (myForm,action,target,onsubmit,ajax,noHistory){
        var submitTarget, rs,origin_target, origin_action;
        if((typeof myForm)=='string') myForm = document.getElementById(myForm);
        //First native onsubmit will benefit to user's onsubmit hook on data validation.
        //1.native onsubmit
        if(myForm.onsubmit){
          rs=null;
          try{rs=myForm.onsubmit();}catch(e){alert(e);return;}
          if(!rs){
            return;
          }
        }
        //2. submit hook
        if(onsubmit){
          rs=null;
          if(typeof onsubmit == "function"){
            try{rs=onsubmit(myForm);}catch(e){alert(e);return;}
          }else{
            rs=eval(onsubmit);
          }
          if(!rs){
            return;
          }
        }
        //3. check target and action
        submitTarget = (null!=target)?target:myForm.target;

        if(!submitTarget) submitTarget=bg.findTarget(myForm);

        if(action==null) action=myForm.action;

        if(action.indexOf("http://")==0) action=action.substring(action.indexOf("/",7));

        if(null==ajax || ajax) ajax=bg.isAjaxTarget(submitTarget);

        // 4. fire
        if(ajax){
          if(null==myForm.id||''==myForm.id){
            myForm.setAttribute("id",myForm.name);
          }
          if(!noHistory && !jQuery("input:file",myForm).length && beangle.ajaxhistory){
            beangle.history.submit(myForm.id,action,submitTarget);
          }else{
            beangle.form.ajaxSubmit(myForm.id,action,submitTarget);
          }
        }else{
          origin_target=myForm.target;
          origin_action=myForm.action;
          myForm.action=action;
          myForm.target = bg.normalTarget(submitTarget);
          myForm.submit();
          myForm.target = origin_target;
          myForm.action = origin_action;
        }
      },
      ajaxSubmit : function(formId,action,target){
        if(!action) action=document.getElementById(formId).action;
        jQuery('#'+formId).ajaxForm({
          success:function(result) {try{jQuery('#'+target).html(result);}catch(e){alert(e)}},
          error:function (response) {try{jQuery('#'+target).html(response.responseText);}catch(e){alert(e)}},
          url:action
        });
        jQuery('#'+formId).submit();
      },
      /**
       * 提交要求含有id的表单
       * @param form 带提交的表单
       * @param id 要提交id的名称
       * @param isMulti(可选)是否允许多个id选择,默认支持一个
       * @param action (可选) 指定form的action
       */
      submitId : function (form,id,isMulti,action,promptMsg,ajax){
        var selectId = bg.input.getCheckBoxValues(id);
        if(null==isMulti) isMulti=false;

        if(""==selectId){
          alert(isMulti?"请选择一个或多个进行操作":"请选择一个进行操作");
          return;
        }
        if(!isMulti && (selectId.indexOf(",")>0)){
          alert("请仅选择一个");
          return;
        }
        if(null!=action){
          form.action=action;
        }else{
          action=form.action;
        }
        bg.form.addInput(form,(isMulti?(id+'s'):id),selectId,"hidden");
        if(null!=promptMsg){
          if(!confirm(promptMsg))return;
        }
        bg.form.submit(form,action,null,null,ajax);
      },
      /**
       * 向form中添加一个input。
       * @param form 要添加输入的form
       * @param name input的名字
       * @param value input的值
       * @param type input的类型,默认为hidden
       * @author chaostone 2006-4-7
       */
      addInput : function (form,name,value,type){
        //防止设置form的属性
        if(form[name]!=null && (typeof form[name].tagName)!="undefined"){
          form[name].value=value;
        }else{
          if(null==type)
            type="hidden";
          var input = document.createElement('input');
          input.setAttribute("name",name);
          input.setAttribute("value",value);
          input.setAttribute("type",type);
          form.appendChild(input);
        }
      },
      ecodeParams : function (params){
        if(""==params)return "";
        var paramsPair=params.split("&"), newParams="", i, eqIndex;
        for(i=0;i
       * 但不收集params的input,这个作为保留名称
       * @param form
       * @param prefix 指明所有input||select的前缀,如果没有前缀可以忽略
       * @param getEmpty 是否收集值为空的属性
       * @return 返回参数列表串形如:&input1=...&input2=...
       * @author chaostone 2006-4-7
       *
       */
      getInputParams : function (form,prefix,getEmpty){
        var elems = form.elements, params = "", i;
        if(null==getEmpty) getEmpty=true;

        for(i = 0;i < elems.length; i++){
          if(""!=elems[i].name){
            if("params"==elems[i].name) continue;
            //alert(elems[i].tagName+":"+elems[i].value);
            if((elems[i].value=="")&&(!getEmpty)) continue;
            if(null!=prefix){
              if(elems[i].name.indexOf(prefix)==0&&elems[i].name.indexOf(".")>1){
                if((elems[i].type=="radio" ||elems[i].type=="checkbox")&& !elems[i].checked)
                  continue;
                if(elems[i].value.indexOf('&')!=-1){
                  params+="&" + elems[i].name + "=" + escape(elems[i].value);
                }else{
                  params+="&" + elems[i].name + "=" + elems[i].value;
                }
              }
            }else{
              if((elems[i].type=="radio" ||elems[i].type=="checkbox")&& !elems[i].checked)
                continue;
              if(elems[i].value.indexOf('&')!=-1){
                params+="&" + elems[i].name + "=" + escape(elems[i].value);
              }else{
                params+="&" + elems[i].name + "=" + elems[i].value;
              }
            }
          }
        }
        //alert("[getInputParams]:"+params);
        return params;
      },
      goToPage : function (form,pageNo,pageSize,orderBy){
        if((typeof form)!="object"){alert("[goToPage:]form is not well defined.");return;}
        //form.method="post"; for avoid "method" input
        if(null!=pageNo){
          if(!/^[1-9]\d*$/.test(pageNo)){
            alert("输入分页的页码是:"+pageNo+",它不是个整数");
            return;
          }
          bg.form.addInput(form,"pageNo",pageNo,"hidden");
        }else{
          bg.form.addInput(form,"pageNo",1,"hidden");
        }
        if(null!=pageSize){
          if(!/^[1-9]\d*$/.test(pageSize)){
            alert("输入分页的页长是:"+pageSize+",它不是个整数");
            return;
          }
          bg.form.addInput(form,"pageSize",pageSize,"hidden");
        }else{
          bg.form.addInput(form,"pageSize","","hidden");
        }
        if(null!=orderBy&&orderBy!="null"){
          bg.form.addInput(form,"orderBy",orderBy,"hidden");
        }else{
          bg.form.addInput(form,"orderBy","","hidden");
        }
        //alert("in goToPage");
        form.submit();
      },
      goToFirstPage : function (form){
        bg.form.goToPage(form,1);
      }
    }
  });

  //select---------------------
  beangle.extend({
    select:{
      getValues : function (select){
        var val = "", i, options = select.options;
        for (i = 0; i< options.length; i++){
          if (val != "")
            val = val + ",";
          val = val + options[i].value;
        }
        return val;
      },
      getSelectedValues : function (select){
        var val = "", i, options = select.options;
        for (i = 0; i < options.length; i++){
          if (options[i].selected){
            if (val != "")
              val = val + ",";
            val = val + options[i].value;
          }
        }
        return val;
      },
      hasOption : function (select, op){
        for (var i = 0; i< select.length; i++ ){
          if (select.options[i].value == op.value)
            return true;
        }
        return false;
      },

      moveSelected : function (srcSelect, destSelect){
        var i, op;
        for (i = 0; i < srcSelect.length; i++){
          if (srcSelect.options[i].selected){
            op = srcSelect.options[i];
            if (!bg.select.hasOption(destSelect, op)){
               destSelect.options[destSelect.length]= new Option(op.text, op.value);
            }
           }
        }
        bg.select.removeSelected(srcSelect);
        bg.select.clearStatus(srcSelect);
      },

      clearStatus : function (select){
        for (var i=0; i0;
      },
      removeSelected : function (select){
        var options = select.options, i;
        for (i = options.length-1; i >= 0; i--){
          if (options[i].selected){
            options[i] = null;
          }
        }
      },
      /**
       * 设定选择框中的选择项(单项)
       */
      setSelected : function (select,idSeq){
        if(idSeq.indexOf(',')!=0){
          idSeq=","+idSeq;
        }
        if(idSeq.lastIndexOf(',')!=idSeq.length-1){
          idSeq=idSeq+",";
        }
        for(var i=0;ithis.maxPageNo){
            pageNo=this.maxPageNo;
          }
        }
        this.paramMap['pageNo']=pageNo;
      }
      if(null!=pageSize){
        if(!/^[1-9]\d*$/.test(pageSize)){
          bg.alert("输入分页的页长是:"+pageSize+",它不是个整数");
          return false;
        }
        this.paramMap["pageSize"]=pageSize;
      }
      if(null!=orderBy && orderBy!="null"){
        this.paramMap["orderBy"]=orderBy;
      }
      return true;
    }
    this.goPage = function (pageNo,pageSize,orderBy){
      var myForm=this.getForm(), key, value;
      if(this.checkPageParams(pageNo,pageSize,orderBy)){
        for(key in this.paramMap){
          value=this.paramMap[key];
          if(value!="")  bg.form.addInput(myForm,key,value,"hidden");
        }
        if(this.target && document.getElementById(this.target)){
          bg.form.ajaxSubmit(this.formid,this.actionurl,this.target);
        }else{
          myForm.submit();
        }
      }
    }
  }

  bg.extend({
    page:function (action,target){return new Page(action,target);}
  });

  bg.onReturn = function(event, action) {
    if (!event) {
      event = window.event;
    }
    if (event && event.keyCode && event.keyCode == 13) {
      action();
    }
  };

  beangle.ready(beangle.iframe.adaptSelf);
  if(beangle.ajaxhistory)beangle.history.init();
})(window);

// fix jquery ready bug
(function(){
    var jqReady = jQuery.prototype.ready;
    jQuery.prototype.ready = function( fn ) {
        return jqReady(function(){
            try{
                fn();
            }catch(e){
                alert(e);
            }
        });
    }
})();




© 2015 - 2025 Weber Informatics LLC | Privacy Policy