utilJs 工具类

RunJS:在线前端代码编辑分享平台是一个在线的 HTML、Javascript、CSS 等 web 前端代码的编辑分享平台,拥有实时预览、高亮显示、代码格式化等功能,提供多种登录方式。

http://runjs.cn/apidoc/classes/Utils.html   --utils.js中方法导航。

http://runjs.cn/apidoc/files/js_utils.js.html  ---代码实际地址


源码方法简介:

  1. /**
  2. * 模块工具类,用来初始化各模块视图、自定绑定事件以及其他辅助功能等
  3. * @class Utils
  4. */
  5. Utils = (function() {
  6.  
  7. var instance;
  8.  
  9. /**
  10. * @class Utils
  11. * @constructor
  12. */
  13. function Utils() {
  14. instance = this;
  15. return this;
  16. }
  17.  
  18. /**
  19. * 事件自动绑定 events:<br>
  20. * 事件映射列表 映射规则:<br>
  21. * "event(事件) -> selector(选择器)":"handler(事件处理器)"<br>
  22. * events = { <br>
  23. * "click->[document]":"doc_click_handler" <br>
  24. * }<br>
  25. * <span style="color:#A00">[注]</span>如果selector带有中括号[]则表明为系统全局变量,如window,document<br>
  26. * 需要以 call(module) 的方式把上下文设置成当前的模块实例
  27. * @example
  28. * g_utils.binder.call(module)
  29. * @method binder
  30. */
  31. Utils.prototype.binder = function() {
  32. var cur = this;
  33. var events = this.Events;
  34. if (isEmpty(events))
  35. return;
  36. var clazz = className(this);
  37. if (isEmpty(clazz))
  38. this.clazz = clazz = "Plugin";
  39. Console.log("[" + clazz + "]Binding events");
  40. try {
  41. $.each(events, function(key, handler) {
  42. if (isEmpty(events))
  43. return;
  44.  
  45. var handler = events[key];
  46. if (isEmpty(key))
  47. return;
  48.  
  49. var sp = key.split("->");
  50. var evt = sp[0];
  51. var sel = sp[1];
  52. if (isEmpty(evt) || isEmpty(sel) || isNotFunc(cur[handler]) && isNotFunc(handler))
  53. return;
  54. var one = function(event) {
  55. if (isNotFunc(handler)) {
  56. cur[handler].call(this, cur, event);
  57. } else {
  58. handler.call(this, cur, event)
  59. }
  60. };
  61. var hasWindowObj = sel.indexOf("[window]") != -1;
  62. var hasDocumentObj = sel.indexOf("[document]") != -1;
  63. if (hasWindowObj) {
  64. $(window).unbind(evt, one);
  65. $(window).bind(evt, one);
  66. sel = sel.replace(/[\[window\]]/g, "")
  67. }
  68.  
  69. if (hasDocumentObj) {
  70. $(document).unbind(evt, one);
  71. $(document).bind(evt, one);
  72. sel = sel.replace(/[\[document\]]/g, "")
  73. }
  74.  
  75. if (isEmpty(sel))
  76. return;
  77.  
  78. Console.log("\t[" + clazz + "]Binding event[" + handler + "]");
  79.  
  80. $(sel).die(evt).live(evt, one);
  81.  
  82. })
  83. } catch (e) {
  84. Console.log("Error Occured When Binding Events:" + e);
  85. }
  86. };
  87.  
  88. /**
  89. * 初始化参数:初始化arguments第一个参数(json格式),将其设置为当前对象的成员属性, params为json格式数据<br>
  90. * @method initParams
  91. * @example
  92. * g_utils.initParams.call(module)
  93. * @params {Object} params JSON类型数据
  94. */
  95. Utils.prototype.initParams = function(params) {
  96. var clazz = className(this);
  97. if (isNotEmpty(params)) {
  98. Console.log("[" + clazz + "]Initializing Params with outer params");
  99. for ( var key in params) {
  100. this[key] = params[key];
  101. }
  102. }
  103. if (isNotEmpty(this.arg) && isNotEmpty(this.arg[0])) {
  104. Console.log("[" + clazz + "]Initializing Params with arguments[0]");
  105. var opt = this.arg[0];
  106. for ( var key in opt) {
  107. if (isNotEmpty(opt[key]))
  108. this[key] = opt[key];
  109. }
  110. }
  111. };
  112.  
  113. /**
  114. * 初始化视图
  115. * 自动像viewLink+"/"+ident路径请求模版,返回后插入到target中,初始化完成执行afterInit回调,并将当前对象当作调用上下文对象
  116. * @method initParams
  117. * @example
  118. * g_utils.initView.call(module,ident,callback,async)
  119. * @param {String} ident 代码的唯一标识
  120. * @param {Function} afterInit 当视图初始化好后调用的回调函数
  121. * @param {Boolean} async 是否采用异步方式加载数据,true或undefined时为异步方式,false为同步方式
  122. */
  123. Utils.prototype.initView = function(ident, afterInit, async) {
  124. var cur = this;
  125. var clazz = className(this);
  126. var func = "on" + clazz + "ViewInit";
  127. if (g_status.once) {
  128. afterInit.call(cur, ident, $(this.target).html());
  129. plugins.fireEvent(func, cur);
  130. return;
  131. }
  132. if (isEmpty(ident))
  133. ident = g_status.ident;
  134. Console.log("[" + this.clazz + "]Initializing View with ident:[" + ident + "] " + (isFunc(afterInit) ? "and callback" : ""));
  135. var link = this.viewLink + "/" + ident + "?" + new Date().getTime();
  136. if (isEmpty(async) || async) {
  137. $.get(link, function(e) {
  138. cur.view = $(e);
  139. Console.log("[" + cur.clazz + "]View Loaded in async");
  140. if (isNotEmpty(cur.target) && isNotEmpty(e)) {
  141. cur.target.html(e);
  142. afterInit.call(cur, ident, cur.view);
  143. plugins.fireEvent(func, cur);
  144. }
  145. });
  146. }else{
  147. var e = instance.load(link,async);
  148. cur.view = $(e);
  149. Console.log("[" + cur.clazz + "]View Loaded in syn");
  150. if (isNotEmpty(cur.target) && isNotEmpty(e)) {
  151. cur.target.html(e);
  152. afterInit.call(cur, ident, cur.view);
  153. plugins.fireEvent(func, cur);
  154. }
  155. }
  156. };
  157.  
  158. /**
  159. * 采用同步或异步方式加载远端资源
  160. * @method load
  161. * @param {String} link 请求链接地址
  162. * @param {Boolean} async 是否采用异步方式加载数据
  163. * @param {Function} callback 采用异步方式的回调函数
  164. * @param {Object} data 发送请求时附带参数数据
  165. * @return {String} responseText 采用同步方式时直接返回结果,采用异步方式时将返回 undefined
  166. */
  167. Utils.prototype.load = function(link, async, callback, data) {
  168. var cur = this;
  169. return $.ajax({
  170. url : link,
  171. success : function(html) {
  172. if (isFunc(callback))
  173. callback.call(cur, html);
  174. },
  175. data : data,
  176. async : async,
  177. type : "post"
  178. }).responseText;
  179. }
  180.  
  181. /**
  182. * 处理服务器端返回的JSON类型数据结果,判断是否为出错信息,并提供两种方式处理错误
  183. * @method errorHandler
  184. * @param {String} msg 服务器传来待处理的 JSON 格式字符串
  185. * @param {Function} success 无错误时的回调函数,该回调将获得处理过后的 JSON 数据
  186. * @param {Function} error 服务器端传来错误信息时调用,将返回出错 JSON 数据
  187. * @param {Boolean} diy 是否立即使用 error 回调函数处理错误,true为立即使用error处理,false和undefined为系统使用弹窗显示错误然后再调用error回调处理
  188. */
  189. Utils.prototype.errorHandler = function(msg, success, error, diy) {
  190. try {
  191. var msg = eval("(" + msg + ")");
  192. if (msg.error) {
  193. if (isEmpty(diy) || !diy) {
  194. dialog.get("error", msg.msg);
  195. if (typeof error != "undefined") {
  196. setTimeout(function() {
  197. error(msg);
  198. }, 2000);
  199. }
  200. return false;
  201. } else {
  202. if (typeof error != "undefined") {
  203. return error(msg);
  204. }
  205. }
  206. }
  207. return success(msg)
  208. } catch (e) {
  209. if (typeof e.stack != 'undefined') {
  210. dialog.get("jserror", e.stack.substring(0, 50));
  211. } else
  212. dialog.get("jserror", e.message);
  213. return;
  214. }
  215. }
  216.  
  217. /**
  218. * 阻止浏览器默认事件
  219. * @method stopDefault
  220. * @param {Object} event 浏览器事件对象
  221. */
  222. Utils.prototype.stopDefault = function(event) {
  223. event.preventDefault();
  224. event.returnvalue = false;
  225. }
  226.  
  227. /**
  228. * 初始状态信息,该方法用来从服务器端加载一段js,用eval执行来初始化全局变量
  229. * @method initStatus
  230. * @param {String} link 请求链接地址
  231. */
  232. Utils.prototype.initStatus = function(link) {
  233. var status = this.load(link, false);
  234. if (isNotEmpty(status))
  235. eval(status);
  236. }
  237.  
  238. /**
  239. * 获得以“http://”开头的链接地址,并加上当前域的HOST名称,例如 g_utils.getHttpLink("/code/abcdefg")将返回"http://runjs.cn/code/abcdefg"
  240. * @method getHttpLink
  241. * @return {String} link 返回处理好的链接地址
  242. */
  243. Utils.prototype.getHttpLink = function(link) {
  244. if (isEmpty(link))
  245. return;
  246. if (link.indexOf("http") == -1) {
  247. if (link.indexOf("/") == 0) {
  248. link = g_status.host + link;
  249. } else {
  250. link = g_status.host + "/" + link;
  251. }
  252. }
  253. return link;
  254. }
  255.  
  256. return Utils;
  257. })();
  258.  
  259. /**
  260. * Utils 类实例[全局]
  261. * @attribute g_utils
  262. */
  263. g_utils = new Utils();
  264.  
  265. /**
  266. * 判断当前对象是否为空
  267. * @method isEmpty
  268. * @param {Object} obj
  269. * @return {Boolean} empty 当为 null,undefined,"" 将返回true
  270. */
  271. window.isEmpty = function(obj) {
  272. return (obj == null || typeof obj == "undefined" || obj.length == 0)
  273. }
  274.  
  275. /**
  276. * 判断当前对象是否非空
  277. * @method isNotEmpty
  278. * @param {Object} obj
  279. * @return {Boolean}
  280. */
  281. window.isNotEmpty = function(obj) {
  282. return !isEmpty(obj);
  283. }
  284.  
  285. /**
  286. * 判断是否为函数
  287. * @method isFunc
  288. * @param {Object} fun
  289. * @return {Boolean}
  290. */
  291. window.isFunc = function(fun) {
  292. return (fun != null && typeof fun == "function");
  293. }
  294.  
  295. /**
  296. * 判断不是函数
  297. * @method isNotFunc
  298. * @param {Object} fun
  299. * @return {Boolean}
  300. */
  301. window.isNotFunc = function(fun) {
  302. return !isFunc(fun);
  303. }
  304.  
  305. /**
  306. * 判断 cur 是否为 type 类型
  307. * @method typeOf
  308. * @param {Object} cur
  309. * @param {String} type
  310. * @example
  311. * typeOf("Hello","string");//将返回true
  312. * @return {Boolean}
  313. */
  314. window.typeOf = function(cur, type) {
  315. if (typeof type != "string")
  316. return false;
  317. return typeof cur == type;
  318. }
  319.  
  320. /**
  321. * 判断是否为数组
  322. * @method isArray
  323. * @param {Object} array
  324. * @return {Boolean}
  325. */
  326. window.isArray = function(array) {
  327. return isNotEmpty(array) && className(array) == "Array"
  328. }
  329.  
  330. /**
  331. * 判断不是数组
  332. * @method isNotArray
  333. * @param {Object} arr
  334. * @return {Boolean}
  335. */
  336. window.isNotArray = function(arr) {
  337. return !isArray(arr);
  338. }
  339.  
  340. /**
  341. * 获取当前模块名
  342. * @method className
  343. * @param {Object} obj
  344. * @example
  345. * className(g_utils);//返回 "Utils"
  346. * @return
  347. */
  348. window.className = function(obj) {
  349. if (obj && obj.constructor && obj.constructor.toString) {
  350. var arr = obj.constructor.toString().match(/function\s*(\w+)/);
  351. if (arr && arr.length == 2) {
  352. obj.clazz = arr[1]
  353. return arr[1];
  354. }
  355. }
  356. return undefined;
  357. }
  358.  
  359. /**
  360. * 判断两个对象是否为相同的类
  361. * @method isSameClass
  362. * @param {Object} cur
  363. * @param {Object} cur2
  364. * @return {Boolean}
  365. */
  366. window.isSameClass = function(cur, cur2) {
  367. if (isNotEmpty(cur) && isNotEmpty(cur2)) {
  368. return className(cur) == className(cur2);
  369. }
  370. return false;
  371. }
  372.  
  373. /**
  374. * 判断两个对象为不同类
  375. * @method isDifClass
  376. * @param {Object} cur
  377. * @param {Object} cur2
  378. * @return {Boolean}
  379. */
  380. window.isDifClass = function(cur, cur2) {
  381. return !isSameClass(cur, cur2);
  382. }
  383.  
  384. /**
  385. * 以 window.open 方式打开弹窗
  386. * @method openwindow
  387. * @param {String} url
  388. * @param {String} name
  389. * @param {Number} iWidth
  390. * @param {Number} iHeight
  391. */
  392. window.openwindow = function(url, name, iWidth, iHeight) {
  393. var url; // 转向网页的地址;
  394. var name; // 网页名称,可为空;
  395. var iWidth; // 弹出窗口的宽度;
  396. var iHeight; // 弹出窗口的高度;
  397. var iTop = (window.screen.availHeight - 30 - iHeight) / 2; // 获得窗口的垂直位置;
  398. var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; // 获得窗口的水平位置;
  399. window.open(url, name, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
  400. }
  401.  
  402. /**
  403. * 返回 true 且啥也不处理的回调函数,用于{{#crossLink "Dialog"}}{{/crossLink}}中设置无所作为的按钮的事件
  404. * @method doNothing
  405. * @example
  406. * dialog.get("confrim2",doNothing,doNow);//doNow 为回调函数
  407. * @return {Boolean}
  408. */
  409. window.doNothing = function() {
  410. return true;
  411. }
  412.  
  413. /**
  414. * 更新浏览器地址栏链接地址
  415. * @method updateUrl
  416. * @param {String} url
  417. */
  418. window.updateUrl = function(url) {
  419. if (window.history && window.history.pushState) {
  420. window.history.pushState(null, url, url);
  421. }
  422. };
  423.  
  424. /**
  425. * 判断当前是否处在iframe中
  426. * @method isIframe
  427. * @return {Boolean}
  428. */
  429. window.isIframe = function() {
  430. return top.location != self.location;
  431. }
  432.  
  433. /**
  434. * 判断当前不处在iframe中
  435. * @method isIframe
  436. * @return {Boolean}
  437. */
  438. window.isNotIframe = function() {
  439. return !isIframe();
  440. };
  441.  
  442. /**
  443. * 利用数组的join构造字符串,提高字符串拼接效率
  444. * @method buildString
  445. * @param arguments {String|Number}
  446. * @return {String} 拼接后的字符串
  447. */
  448. window.buildString = function(){
  449. var str = [];
  450. for(var i=0;i<arguments.length;i++){
  451. str[i] = arguments[i];
  452. }
  453. return str.join("");
  454. };
  455.  
  456. window.console = window.console || {};
  457.  
  458. console.log || (console.log = typeof opera != "undefined" ? opera.postError : function(msg) {
  459. });
  460.  
  461. /*---IE Extend---*/
  462. if (!Array.prototype.indexOf) {
  463. Array.prototype.indexOf = function(elt /* , from */) {
  464. var len = this.length >>> 0;
  465.  
  466. var from = Number(arguments[1]) || 0;
  467. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  468. if (from < 0)
  469. from += len;
  470.  
  471. for (; from < len; from++) {
  472. if (from in this && this[from] === elt)
  473. return from;
  474. }
  475. return -1;
  476. };
  477. }
  478.  
  479. ConsoleUtils = (function(){
  480. var open = false;
  481. function ConsoleUtils(op){
  482. open = op;
  483. }
  484. ConsoleUtils.prototype.toggle = function(){
  485. open = !open;
  486. };
  487. ConsoleUtils.prototype.open = function(){
  488. open = true;
  489. }
  490. ConsoleUtils.prototype.close = function(){
  491. open = false;
  492. }
  493. ConsoleUtils.prototype.log = function(msg){
  494. if(open)
  495. console.log(msg);
  496. }
  497. return ConsoleUtils;
  498. })();
  499.  
  500. Console = new ConsoleUtils(false);



项目中用到的工具包:

/********************************************
 * 
 * date:   2017-3-15
 * Modify: add annotation
 * author: jiankangcui
 * 
 * ******************************************/
define([
        'jquery',
        'global',
        'numeral'
        ],
function($,global){


var i = 0;
var name;
var Util = function(){
this.prefixRendered=false;
};
var submitOptions={
context:null,//提交表单域 
action:null,//提交url
dataExtension:null,//额外数据
mode:''
};


var renderOptions={
context:null,//渲染表单域
url:null,//提交url
formDataSelector: null
};


Util.prototype = {


//打开一个新的标签页的窗口
new_window : function(item){
var url    = $(item).attr('data-url')||$(item).attr('href'),
  width  = $(item).attr('data-width')||500,
  height = $(item).attr('data-height')||800,
  left   = Math.max(0,$(window).width()/2 - width/2);
return window.open(url,'_blank','width='+ width +',height='+ height +',top=100,left='+left+',toolbar=no,menubar=no,scrollbars=yes, resizable=yes,location=no, status=no');
},


stringify_aoData : function (aoData) {
   var o = {};
   var modifiers = ['mDataProp_',
                 'sSearch_',
                 'iSortCol_',
                 'bSortable_',
                 'bRegex_',
                 'bSearchable_',
                 'sSortDir_'];
   $.each(aoData, function(idx,obj) {
       if (obj.name) {
           for (i=0; i < modifiers.length; i++) {
               if (obj.name.substring(0, modifiers[i].length) === modifiers[i]) {
                   var index = parseInt(obj.name.substring(modifiers[i].length), 10);
                   var key = 'a' + modifiers[i].substring(0, modifiers[i].length-1);
                   if (!o[key]) {
                       o[key] = [];
                   }
                   o[key][index] = obj.value;
                   return;
               }
           }
           o[obj.name] = obj.value;
       }
       else {
           o[idx] = obj;
       }
   });
   return JSON.stringify(o);
},


//配置菜单激活状态样式
set_menu: function(item){
$('.navbar-fixed-top .navbar-nav li').removeClass('active');
$('.navbar-fixed-top .navbar-nav li').each(function(i){
var menuItem = $(this).attr('data-menu-item');
if(menuItem === item){
$(this).addClass('active');
}
});
},


ajax_submit: function(form,option){
option=option||submitOptions;
//获取form元素
var rootElement=option.context?('#'+$(form).attr('id')+' '+option.context):form;
//获取form元素的id
var formId=option.context?($(form).attr('id')+' '+option.context):$(form).attr('id');
var result ={};


if(option.context1&&option.context1==='.flat'){
var rootElement1=option.context1?('#'+$(form).attr('id')+' '+option.context1):form;
result = this._clone( this._submit_data(rootElement1,option));
}
if(option.mode && option.mode==='arrayMode'){
var firstRootElement=option.list?('#'+$(form).attr('id')+' '+option.list):form;
formId = $(form).attr('id');
for(i=1;i<=$(firstRootElement).length;i++){
var listAttr='';
var arr = [];
var secondRootElement = option.context?('#'+$(form).attr('id')+' '+option.list+'-'+i+' '+option.context):form;
for(var j=0;j<$(secondRootElement).length;j++){
var temp = secondRootElement;
temp = temp + ':eq('+j+')';
var data =this._submit_data(temp,option);
arr.push(this._clone(data));
listAttr=temp;
}
result[$(listAttr).attr('data-name')]=arr;
}


return $.ajax({
url: option.action||$(form).attr('action'),
type: $(form).attr('method'),
dataType: 'json',
headers: {
'x-form-id' : formId
},
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(result)

});
}
//引用提取ajax数据函数
var data1 = this._submit_data(rootElement,option);
//发送ajax请求 
return $.ajax({
url: option.action||$(form).attr('action'),
type: $(form).attr('method'),
dataType: 'json',
headers: {
'x-form-id' : formId
},
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify(data1)
});
},


//提取ajax数据,返回对象
_submit_data: function(rootElement,option){
var rootElement1 = rootElement;
var o = {};
var key;
var tokens;
var t;
var c;
var option1 = option;
$(rootElement1).find('input,textarea,select,.file-upload,.data-binder').each(function(){
if($(this).attr('data-ignore')==='true'||$(this).parents('[data-ignore=true]').length>0){
return true;
}
if($(this).attr('type')==='file'){
return true;
}
if($(this).hasClass('select2-focusser select2-offscreen') || $(this).hasClass('select2-input')){
return true;
}
key = $(this).attr('name');
if(key){
tokens = key.split('\.');
c = o;
for(i=0; i<tokens.length; i++){
t = tokens[i]; 
if(!c.hasOwnProperty(t)){ 
c[t] = {};
}


if(i === tokens.length -1){
if($(this).hasClass('file-upload')){
c[t] = $(this).attr('data-img');
}
else if($(this).hasClass('data-binder')){
c[t] = $(this).attr('data-val');
}
else if($(this).attr('type') === 'checkbox'){
c[t] = $(this).is(':checked');
}
else if($(this).attr('type') === 'radio')
{
if($(this).is(':checked'))
{
c[t] = $(this).val();
}
}else{
c[t] = $(this).val();
}
}else{
c = c[t];
}
}
}
});
//加入额外数据
if(option1.dataExtension&&typeof option1.dataExtension==='object'){
for(var prop in option1.dataExtension){
if(prop === 'masked_data'){
var masked_data = option1.dataExtension[prop];
for(var mask in masked_data){
var ligten_data = o[mask.slice(0,mask.indexOf('_original'))];
if(ligten_data && ligten_data.indexOf('*') !== -1){
o[mask.slice(0,mask.indexOf('_original'))] = masked_data[mask];
}
}
}else{
o[prop]=option1.dataExtension[prop];
}

}
}
return o;
},


_render_data: function(root,data,option){
            var me = this;
$(root).find('input,select,.hidden-form-control,.file-upload,.show-form-control,textarea').each(function(){
var $this = $(this);
name = $this.attr('name');
if(name)
{
var s = name.split('.');
var temp = data;
for(i=0;i<s.length;i++)
{
if(temp){ temp = temp[s[i]]; }
}


if(temp!= undefined && temp != null){
if($(this).attr('type') === 'radio' || $(this).attr('type') === 'checkbox'){
$(this).prop('checked',temp);
}else if($(this).hasClass('select2-hidden')){
$(this).select2('val', temp);
}
else if($(this).hasClass('file-upload')){
$(this).attr('data-img',temp);
$(this).find('.file-binder').val(temp);
$(this).find('.upload-filename').text(temp);
}
else if(this.tagName === 'SPAN')
{
$this.html(temp).attr('title',temp);
}else if(this.tagName === 'IMG'){
                             if(me.is_pdf(temp)) {
                                $this.attr('src',global.context+'/assets/img/pdf.jpg');
                                $this.attr('data-pdfpath',temp);
                                $(this).parent().find('.file-upload .upload-img').attr('src',global.context+'/assets/img/pdf.jpg');
                                $(this).parent().find('.file-upload .upload-img').attr('data-pdfpath',temp);
                            }else if(me.is_doc(temp)) {
                                $this.attr('src',global.context+'/assets/img/doc.jpg');
                                $this.attr('data-pdfpath',temp);
                                $(this).parent().find('.file-upload .upload-img').attr('src',global.context+'/assets/img/doc.jpg');
                                $(this).parent().find('.file-upload .upload-img').attr('data-pdfpath',temp);
                            }
                             else{
                                $this.attr('src',temp);
                                $this.removeAttr('data-pdfpath');
                                $(this).parent().find('.file-upload .upload-img').attr('src',temp);
                                $(this).parent().find('.file-upload .upload-img').removeAttr('data-pdfpath');
                            }
                            $(this).parent().find('.file-upload .upload-img').parent('.upload-thumbnail').show();


}else{
var except = option.except || [];
var flat = false;
for(i=0;i<except.length;i++)
{
if(option.except[i] === $this.attr('name'))
{
flat = true;
}
}
if(flat){
name = temp.name || '';
$this.val(name);
}else{
$this.val(temp);
}
}
}
}

});
},


render_form : function(form,option){
var that = this; 
this.render_prefix(form,option);
option=option||renderOptions;
var rootElement=option.context?('#'+$(form).attr('id')+' '+option.context):form;
var formDataSelector = option.formDataSelector;
var formData=$(rootElement).data('cache');
if(option.cache && formData){
this._render_data(rootElement,formData,option);
return;
}
if(formDataSelector)
{
var jsontext = $.trim($(formDataSelector).text()).length===0?'{}':$(formDataSelector).text();
formData = $.parseJSON(jsontext);
this._render_data(rootElement,formData,option);
return;
}
return $.ajax({
url: option.url,
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=UTF-8'
}).done(function(resp){
$(rootElement).data('cache',resp);
that._render_data(rootElement,resp,option);
});
},


render_prefix:function(form,option){
if(this.prefixRendered){
return;
}
option=option||renderOptions;
var rootElement=option.context?('#'+$(form).attr('id')+' '+option.context):'form';
$(rootElement).find('input,select,.hidden-form-control,.file-upload,.data-binder,.show-form-control,textarea').each(function(){
if($(this).hasClass('upload-input')){
return;
}
var currentName=$(this).attr('name')?$(this).attr('name'):'';
var parentName=$(this).parents('.hasPrefix').length>0?$(this).parents('.hasPrefix').eq(0).attr('data-prefix'):'';
$(this).attr('name',parentName+currentName);
});
this.prefixRendered=true;
},


//http 重定向
//replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串
redirect: function(url) {
            // Similar behavior as an HTTP redirect
            window.location.replace(url);
        },


        //form表单数据提取(包含单选框、复选框)
        getSearchData:function(containerId){
        var result = [];
       $(containerId).find('input,textarea,select').each(function(){
var o = {};
var key;
if($(this).attr('data-ignore')==='true'){
return true;
}
if($(this).hasClass('select2-focusser select2-offscreen') || $(this).hasClass('select2-input')){
return true;
}
key = $(this).attr('name');
if(key){
if($(this).attr('Type')==='checkbox'){
o['name'] = key;
if($(this).val()==='true'){
o['value']=true;
}else{
o['value']=false;
}
}
else if($(this).attr('Type')==='radio'){
if($(this).is(':checked')){
o['name'] = key;
o['value']= $(this).val();
} else {
return;
}
}else{
o['name'] = key;
o['value']=$(this).val();
}
result.push(o);
}
});
return result;
        },


        //克隆对象为新对象 for(i in myObj)
        _clone: function(myObj){
        if(typeof(myObj) !== 'object') return myObj;
  if(myObj == null){ return myObj; }


  var myNewObj = {};


  for(i in myObj){
  myNewObj[i] = this._clone(myObj[i]);
  }


  return myNewObj;
        },
        
        //数字保留小数位
    _decimal_floor: function(digit, length) {  
       length = length ? parseInt(length, 10) : 0;  
       if (length <= 0){ return Math.floor(digit); }  
       digit = Math.floor(digit * Math.pow(10, length)) / Math.pow(10, length);  
       return digit;  
    },


    //添加千位分隔符,保留两位小数
    get_thousand_floor: function(num,length){
    if(!length){
    length = 2;
    };
    num = this._decimal_floor(num,length);
    return numeral(num).format('0,0.00');
    },


    //添加千位分隔符,保留两位小数
        get_thousand:function(num){
           if(!isNaN(num)){
          return numeral(num).format('0,0.00');
           }
           else {
          return '0.00';
           }
        },
        
        //匹配小数点,整数保留一位小数
        get_aprate:function(num){
        var data = parseFloat(num);
        return !/\./.test(data) == true? data += '.0':data;
        },
        
        //匹配格式‘0.0’的百分数
        get_percent:function(num){
            return numeral(num).format('0.0')+'%';
        },
        
        //匹配小数点,整数保留一位小数添加 ‘%’
        get_trans_percent:function(num){
        if(num.indexOf('.')!==-1){
        return num+'%';
        }else{
        return num+'.0%';
        }
        },
        
        //匹配格式‘0.00’,整数保留两位小数
        get_twoScale:function(num){
        return numeral(num).format('0.00');
        },
        
        //判断链接文件类型pdf
        is_pdf:function(path){
            var type = path.substr(path.length-3).toLowerCase();
            if(type==='pdf'){ return true; }
            else{ return false; }
        },
        
        //判断链接文件类型doc
        is_doc:function(path){
        var array=path.split('.');
            return array.length>0&&(array[array.length-1]==='doc'||array[array.length-1]==='docx');
        },
        
        //判断链接文件类型excel
        is_excel:function(path){
        var array=path.split('.');
            return array.length>0&&(array[array.length-1]==='xls'||array[array.length-1]==='xlsx');
        },
        
        //form表单数据提取
        get_search_data:function(form_selector){
        var val;
        var data = {};
        $(form_selector).find('input,select,textarea').each(function(){
        var $this = $(this);
        if($this.attr('data-ignore') === 'true'){
        return;
        }
        name = $this.attr('name');
        if($this.attr('data-userSel') === 'true'){
        val = $this.data('value');
        }else{
        val = $this.val();
        }
        if( !data.hasOwnProperty(name) || $.trim(val).length>0){
        data[name] = val;
        }


        });
        return data;
    },
   
    //form表单数据提取(包含单选框)
        get_search_radio:function(form_selector){
        var name1;
        var val1;
        var data = {};
        $(form_selector).find('input,select,textarea').each(function(){
        var $this = $(this);
        if($this.attr('data-ignore') === 'true'){
        return;
        }
        if($(this).attr('Type')==='radio'){
        if($(this).is(':checked')){
        name1 = $this.attr('name');
                val1 = $this.val();
        }
        }else{
        name1 = $this.attr('name');
            val1 = $this.val();
        }
       
        if( !data.hasOwnProperty(name1) || $.trim(val1).length>0){
        data[name1] = val1;
        }


        });
        return data;
    },


    //bootstrap-popover-x 侧边弹出框(**)
    bind_popoverx:function(selector,width,height){
    var iselector = selector || '.image-example-popoverx';
    var iwidth = width || 204;
    var iheight = height || 151;
    $(iselector).popoverx({
    ensure_visiable : true,
    trigger: 'hover',
    placement : 'top',
    width: iwidth,
    height: iheight,
    elementToAppend:  $('.right-blk-body').length===0? $('.blk-body'):  $('.right-blk-body'),
    onShown: function(){
    var src = $(this.element).attr('data-src');
    var html = '<img src="'+src+'" width="100%";></img>';
    this.$tip.find('.popover-content').html(html);
    this.resetPosition();
    }
    });
    },
   
    //时间戳转日期
    unixToDate: function(unixTime, isFull, timeZone) {
            if (typeof (timeZone) === 'number')
            {
                unixTime = parseInt(unixTime, 10) + parseInt(timeZone, 10) * 60 * 60;
            }
            var time = new Date(unixTime);
            var ymdhis = '';
            var year = time.getFullYear();
            var month = time.getMonth()+1;
            var date = time.getDate();
            var hours = time.getHours();
            var minutes = time.getMinutes();
            var seconds = time.getSeconds();


            month = month < 10 ? '0'+month : month;
            date = date < 10 ? '0'+date : date;
            hours = hours < 10 ? '0'+hours : hours;
            minutes = minutes < 10 ? '0'+minutes : minutes;
            seconds = seconds < 10 ? '0'+seconds : seconds;


            ymdhis += year + '-' + month + '-' + date;
            if (isFull === true)
            {
                ymdhis += ' ' + hours + ':' + minutes + ':' + seconds;
            }
            return ymdhis;
        }
};
return new Util();
});

你可能感兴趣的:(js工具类)