bjui-extends.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. /*!
  2. * B-JUI v1.2 (http://b-jui.com)
  3. * Git@OSC (http://git.oschina.net/xknaan/B-JUI)
  4. * Copyright 2014 K'naan (xknaan@163.com).
  5. * Licensed under Apache (http://www.apache.org/licenses/LICENSE-2.0)
  6. */
  7. /* ========================================================================
  8. * B-JUI: bjui-extends.js v1.2
  9. * @author K'naan (xknaan@163.com)
  10. * -- Modified from dwz.core.js (author:ZhangHuihua@msn.com)
  11. * http://git.oschina.net/xknaan/B-JUI/blob/master/BJUI/js/bjui-extends.js
  12. * ========================================================================
  13. * Copyright 2014 K'naan.
  14. * Licensed under Apache (http://www.apache.org/licenses/LICENSE-2.0)
  15. * ======================================================================== */
  16. +function ($) {
  17. 'use strict';
  18. $.fn.extend({
  19. /**
  20. * @param {Object} op: {type:GET/POST, url:ajax请求地址, data:ajax请求参数列表, callback:回调函数 }
  21. */
  22. ajaxUrl: function(op) {
  23. var $this = $(this)
  24. $this.trigger(BJUI.eventType.beforeAjaxLoad)
  25. if (op.loadingmask) {
  26. $this.trigger(BJUI.eventType.ajaxStatus)
  27. }
  28. $.ajax({
  29. type : op.type || 'GET',
  30. url : op.url,
  31. data : op.data || {},
  32. cache : false,
  33. dataType : 'html',
  34. timeout : BJUI.ajaxTimeout,
  35. success : function(response) {
  36. var json = response.toJson(), $ajaxMask = $this.find('> .bjui-ajax-mask')
  37. if (!json[BJUI.keys.statusCode]) {
  38. $this.empty().html(response).append($ajaxMask).initui()
  39. if ($.isFunction(op.callback)) op.callback(response)
  40. } else {
  41. if (json[BJUI.keys.statusCode] == BJUI.statusCode.error) {
  42. if (json[BJUI.keys.message]) $this.alertmsg('error', json[BJUI.keys.message])
  43. if (!$this.closest('.bjui-layout').length) {
  44. if ($this.closest('.navtab-panel').length) $this.navtab('closeCurrentTab')
  45. else $this.dialog('closeCurrent')
  46. }
  47. } else if (json[BJUI.keys.statusCode] == BJUI.statusCode.timeout) {
  48. if ($this.closest('.bjui-dialog').length) $this.dialog('closeCurrent')
  49. if ($this.closest('.navtab-panel').length) $this.navtab('closeCurrentTab')
  50. $('body').alertmsg('info', (json[BJUI.keys.message] || BJUI.regional.sessiontimeout))
  51. BJUI.loadLogin()
  52. }
  53. $ajaxMask.fadeOut('normal', function() {
  54. $(this).remove()
  55. })
  56. }
  57. },
  58. error : function(xhr, ajaxOptions, thrownError) {
  59. $this.bjuiajax('ajaxError', xhr, ajaxOptions, thrownError)
  60. if (!$this.closest('.bjui-layout').length) {
  61. if ($this.closest('.navtab-panel').length) $this.navtab('closeCurrentTab')
  62. else $this.dialog('closeCurrent')
  63. }
  64. $this.trigger('bjui.ajaxError')
  65. },
  66. statusCode : {
  67. 503: function(xhr, ajaxOptions, thrownError) {
  68. $this.alertmsg('error', FRAG.statusCode_503.replace('#statusCode_503#', BJUI.regional.statusCode_503) || thrownError)
  69. }
  70. }
  71. })
  72. },
  73. loadUrl: function(url,data,callback) {
  74. $(this).ajaxUrl({url:url, data:data, callback:callback})
  75. },
  76. doAjax: function(op) {
  77. var $this = $(this), $target, $ajaxMask
  78. if (!op.url) {
  79. BJUI.debug('The ajax url is undefined!')
  80. return
  81. }
  82. if (!op.callback) {
  83. BJUI.debug('The ajax callback is undefined!')
  84. return
  85. } else {
  86. op.callback = op.callback.toFunc()
  87. }
  88. if (op.loadingmask) {
  89. $target = $this.getPageTarget()
  90. $target.trigger(BJUI.eventType.ajaxStatus)
  91. $ajaxMask = $target.find('> .bjui-ajax-mask')
  92. }
  93. if (!op.type) op.type = 'POST'
  94. if (!op.dataType) op.dataType = 'json'
  95. if (!op.cache) op.cache = false
  96. op.timeout = BJUI.ajaxTimeout
  97. op.success = function(response) {
  98. if ($ajaxMask) {
  99. if (op.callback) {
  100. $.when(op.callback(response)).done(function() {
  101. $target.trigger('bjui.ajaxStop')
  102. })
  103. } else {
  104. $target.trigger('bjui.ajaxStop')
  105. }
  106. } else {
  107. op.callback(response)
  108. }
  109. }
  110. op.error = op.error || function(xhr, ajaxOptions, thrownError) {
  111. $this.bjuiajax('ajaxError', xhr, ajaxOptions, thrownError)
  112. if ($ajaxMask) {
  113. $target.trigger('bjui.ajaxError')
  114. }
  115. }
  116. $.ajax(op)
  117. },
  118. getPageTarget: function() {
  119. var $target
  120. if (this.closest('.bjui-layout').length) $target = this.closest('.bjui-layout')
  121. else if (this.closest('.navtab-panel').length) $target = $.CurrentNavtab
  122. else $target = $.CurrentDialog
  123. return $target
  124. },
  125. resizePageH: function() {
  126. return this.each(function() {
  127. if ($(this).closest('.tab-content').length) return
  128. var $box = $(this),
  129. $pageHeader = $box.find('> .bjui-pageHeader'),
  130. $pageContent = $box.find('> .bjui-pageContent'),
  131. $pageFooter = $box.find('> .bjui-pageFooter'),
  132. headH = $pageHeader.outerHeight() || 0,
  133. footH = $pageFooter.outerHeight() || 0
  134. if ($box.hasClass('navtabPage') && $box.is(':hidden')) {
  135. $box.show()
  136. headH = $pageHeader.outerHeight() || 0
  137. footH = $pageFooter.outerHeight() || 0
  138. $box.hide()
  139. }
  140. if ($pageFooter.css('bottom')) footH += parseInt($pageFooter.css('bottom')) || 0
  141. if (footH == 0 && $box.hasClass('dialogContent')) footH = 5
  142. $pageContent.css({top:headH, bottom:footH})
  143. })
  144. },
  145. getMaxIndexObj: function($elements) {
  146. var zIndex = 0, index = 0
  147. $elements.each(function(i) {
  148. var newZIndex = parseInt($(this).css('zIndex')) || 1
  149. if (zIndex < newZIndex) {
  150. zIndex = newZIndex
  151. index = i
  152. }
  153. })
  154. return $elements.eq(index)
  155. },
  156. /**
  157. * 将表单数据转成JSON对象 用法:$(form).serializeJson() Author: K'naan
  158. */
  159. serializeJson: function () {
  160. var o = {}
  161. var a = this.serializeArray()
  162. $.each(a, function () {
  163. if (o[this.name] !== undefined) {
  164. if (!o[this.name].push) {
  165. o[this.name] = [o[this.name]]
  166. }
  167. o[this.name].push(this.value || '')
  168. } else {
  169. o[this.name] = this.value || ''
  170. }
  171. })
  172. return o
  173. },
  174. isTag: function(tn) {
  175. if (!tn) return false
  176. if (!$(this).prop('tagName')) return false
  177. return $(this)[0].tagName.toLowerCase() == tn ? true : false
  178. },
  179. /**
  180. * 判断当前元素是否已经绑定某个事件
  181. * @param {Object} type
  182. */
  183. isBind: function(type) {
  184. var _events = $(this).data('events')
  185. return _events && type && _events[type]
  186. },
  187. /**
  188. * 输出firebug日志
  189. * @param {Object} msg
  190. */
  191. log: function(msg) {
  192. return this.each(function() {
  193. if (console) console.log('%s: %o', msg, this)
  194. })
  195. }
  196. })
  197. /**
  198. * 扩展String方法
  199. */
  200. $.extend(String.prototype, {
  201. isPositiveInteger: function() {
  202. return (new RegExp(/^[1-9]\d*$/).test(this))
  203. },
  204. isInteger: function() {
  205. return (new RegExp(/^\d+$/).test(this))
  206. },
  207. isNumber: function() {
  208. return (new RegExp(/^([-]{0,1}(\d+)[\.]+(\d+))|([-]{0,1}(\d+))$/).test(this))
  209. },
  210. includeChinese: function() {
  211. return (new RegExp(/[\u4E00-\u9FA5]/).test(this))
  212. },
  213. trim: function() {
  214. return this.replace(/(^\s*)|(\s*$)|\r|\n/g, '')
  215. },
  216. startsWith: function (pattern) {
  217. return this.indexOf(pattern) === 0
  218. },
  219. endsWith: function(pattern) {
  220. var d = this.length - pattern.length
  221. return d >= 0 && this.lastIndexOf(pattern) === d
  222. },
  223. replaceSuffix: function(index) {
  224. return this.replace(/\[[0-9]+\]/,'['+index+']').replace('#index#',index)
  225. },
  226. replaceSuffix2: function(index) {
  227. return this.replace(/\-(i)([0-9]+)$/, '-i'+ index).replace('#index#', index)
  228. },
  229. trans: function() {
  230. return this.replace(/&lt;/g, '<').replace(/&gt;/g,'>').replace(/&quot;/g, '"')
  231. },
  232. encodeTXT: function() {
  233. return (this).replaceAll('&', '&amp;').replaceAll('<','&lt;').replaceAll('>', '&gt;').replaceAll(' ', '&nbsp;')
  234. },
  235. replaceAll: function(os, ns) {
  236. return this.replace(new RegExp(os,'gm'), ns)
  237. },
  238. /*替换占位符为对应选择器的值*/ //{^(.|\#)[A-Za-z0-9_-\s]*}
  239. replacePlh: function($box) {
  240. $box = $box || $(document)
  241. return this.replace(/{\/?[^}]*}/g, function($1) {
  242. var $input = $box.find($1.replace(/[{}]+/g, ''))
  243. return $input && $input.val() ? $input.val() : $1
  244. })
  245. },
  246. replaceMsg: function(holder) {
  247. return this.replace(new RegExp('({.*})', 'g'), holder)
  248. },
  249. replaceTm: function($data) {
  250. if (!$data) return this
  251. return this.replace(RegExp('({[A-Za-z_]+[A-Za-z0-9_-]*})','g'), function($1) {
  252. return $data[$1.replace(/[{}]+/g, '')]
  253. })
  254. },
  255. replaceTmById: function(_box) {
  256. var $parent = _box || $(document)
  257. return this.replace(RegExp('({[A-Za-z_]+[A-Za-z0-9_-]*})','g'), function($1) {
  258. var $input = $parent.find('#'+ $1.replace(/[{}]+/g, ''))
  259. return $input.val() ? $input.val() : $1
  260. })
  261. },
  262. isFinishedTm: function() {
  263. return !(new RegExp('{\/?[^}]*}').test(this))
  264. },
  265. skipChar: function(ch) {
  266. if (!this || this.length===0) return ''
  267. if (this.charAt(0)===ch) return this.substring(1).skipChar(ch)
  268. return this
  269. },
  270. isValidPwd: function() {
  271. return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this))
  272. },
  273. isValidMail: function() {
  274. return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()))
  275. },
  276. isSpaces: function() {
  277. for (var i = 0; i < this.length; i += 1) {
  278. var ch = this.charAt(i)
  279. if (ch!=' '&& ch!='\n' && ch!='\t' && ch!='\r') return false
  280. }
  281. return true
  282. },
  283. isPhone:function() {
  284. return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this))
  285. },
  286. isUrl:function() {
  287. return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this))
  288. },
  289. isExternalUrl:function() {
  290. return this.isUrl() && this.indexOf('://'+ document.domain) == -1
  291. },
  292. toBool: function() {
  293. return (this.toLowerCase() === 'true') ? true : false
  294. },
  295. toJson: function() {
  296. var json = this
  297. try {
  298. if (typeof json == 'object') json = json.toString()
  299. if (!json.trim().match("^\{(.+:.+,*){1,}\}$")) return this
  300. else return JSON.parse(this)
  301. } catch (e) {
  302. return this
  303. }
  304. },
  305. toObj: function() {
  306. var obj = null
  307. try {
  308. obj = (new Function('return '+ this))()
  309. } catch (e) {
  310. obj = this
  311. BJUI.debug('String toObj:Parse "String" to "Object" error! Your str is: '+ this)
  312. }
  313. return obj
  314. },
  315. /**
  316. * String to Function
  317. * 参数(方法字符串或方法名): 'function(){...}' 或 'getName' 或 'USER.getName' 均可
  318. * Author: K'naan
  319. */
  320. toFunc: function() {
  321. if (!this || this.length == 0) return undefined
  322. //if ($.isFunction(this)) return this
  323. if (this.startsWith('function')) {
  324. return (new Function('return '+ this))()
  325. }
  326. var m_arr = this.split('.')
  327. var fn = window
  328. for (var i = 0; i < m_arr.length; i++) {
  329. fn = fn[m_arr[i]]
  330. }
  331. if (typeof fn === 'function') {
  332. return fn
  333. }
  334. return undefined
  335. },
  336. setUrlParam: function(key, value) {
  337. var str = '', url = this
  338. if (url.indexOf('?') != -1)
  339. str = url.substr(url.indexOf('?') + 1)
  340. else
  341. return url + '?' + key + '=' + value
  342. var returnurl = '', setparam = '', arr, modify = '0'
  343. if (str.indexOf('&') != -1) {
  344. arr = str.split('&')
  345. for (var i in arr) {
  346. if (arr[i].split('=')[0] == key) {
  347. setparam = value
  348. modify = '1'
  349. } else {
  350. setparam = arr[i].split('=')[1]
  351. }
  352. returnurl = returnurl + arr[i].split('=')[0] + '=' + setparam + '&'
  353. }
  354. returnurl = returnurl.substr(0, returnurl.length - 1)
  355. if (modify == '0') {
  356. if (returnurl == str)
  357. returnurl = returnurl + '&' + key + '=' + value
  358. }
  359. } else {
  360. if (str.indexOf('=') != -1) {
  361. arr = str.split('=')
  362. if (arr[0] == key) {
  363. setparam = value
  364. modify = '1'
  365. } else {
  366. setparam = arr[1]
  367. }
  368. returnurl = arr[0] + '=' + setparam
  369. if (modify == '0') {
  370. if (returnurl == str)
  371. returnurl = returnurl + '&' + key + '=' + value
  372. }
  373. } else {
  374. returnurl = key + '=' + value
  375. }
  376. }
  377. return url.substr(0, url.indexOf('?')) + '?' + returnurl
  378. }
  379. })
  380. /* Function */
  381. $.extend(Function.prototype, {
  382. //to fixed String.prototype -> toFunc
  383. toFunc: function() {
  384. return this
  385. }
  386. })
  387. /* Array */
  388. $.extend(Array.prototype, {
  389. remove: function(index) {
  390. if (index < 0) return this
  391. else return this.slice(0, index).concat(this.slice(index + 1, this.length))
  392. },
  393. unique: function() {
  394. var temp = new Array()
  395. this.sort()
  396. for (var i = 0; i < this.length; i++) {
  397. if (this[i] == this[i + 1]) continue
  398. temp[temp.length] = this[i]
  399. }
  400. return temp
  401. },
  402. myIndexOf: function(e) {
  403. if (!this || !this.length) return -1
  404. for (var i = 0, j; j = this[i]; i++) {
  405. if (j == e) return i
  406. }
  407. return -1
  408. },
  409. /* serializeArray to json */
  410. toJson: function() {
  411. var o = {}
  412. var a = this
  413. $.each(a, function () {
  414. if (o[this.name] !== undefined) {
  415. if (!o[this.name].push) {
  416. o[this.name] = [o[this.name]]
  417. }
  418. o[this.name].push(this.value || '')
  419. } else {
  420. o[this.name] = this.value || ''
  421. }
  422. })
  423. return o
  424. }
  425. })
  426. /* Global */
  427. $.isJson = function(obj) {
  428. var flag = true
  429. try {
  430. flag = $.parseJSON(obj)
  431. } catch (e) {
  432. return false
  433. }
  434. return flag ? true : false
  435. }
  436. }(jQuery);