define(function(require, exports, module) { require('bus/global/main'); //依赖 var $ = require('$'), handlerbars = require('common/handlerbars'), Ajax = require('model/ajax/main'), Validator = require('common/validator'), ImgView = require('model/imgView/main'), CascadeSelect = require('model/cascadeSelect/main'), //级联选择 Scroller = require('common/scroller'); var validatorExp = Validator.use('#caseManage-form'); $("#save").on('click',function(){ validatorExp.execute(function(flag, err){ if(!flag){ new Ajax({ request: "../LassenCourtAssignRpc/saveLassenCourtAssign.json?securityCaseId="+encodeURIComponent($("input[name='securityCaseId']").val()), paramName: "lassenCourtAssignDo", parseForm: $("#caseManage-form") }).on('ajaxSuccess', function(rtv, msg, con){ displayResult(rtv, msg, con); // location.reload(); }).submit(); } }); }); // 组件:图片查看 new ImgView(); //显示静态页面,删除form function displayResult(){ var result = {}; result.deptName = $("input[name='deptName']").val(); result.trialName = $("input[name='trialName']").val(); result.clerkName = $("input[name='clerkName']").val(); result.remark = $("[name='remark']").val(); var templat = handlerbars.compile($('#template').html()); $('.content').html(templat(result)); $("#caseManage-form").remove(); } //添加事件 $("#load-more-details").on('click', function(){ $("#more-details").removeClass("fn-hide"); Scroller.use('.JS-need-scroller'); $("#load-more-details").css("display","none"); }); $(".JS-trigger-more-information").on('click', function(e){ $("#court-more-information").removeClass("fn-hide"); //组件:滚动条 Scroller.use('.JS-need-scroller'); $(e.target).parent().remove(); }); $('[name="trialId"]').on('change', function(e){ var trialCourt = $(e.target); $('[name="trialName"]').val(trialCourt.find('option:selected').text()); }); $('[name="clerkId"]').on('change', function(e){ var clerk = $(e.target); $('[name="clerkName"]').val(clerk.find('option:selected').text()); }); $('[name="deptId"]').on('change', function(e){ var dept = $(e.target); $('[name="deptName"]').val(dept.find('option:selected').text()); $('[name="trialName"]').val(''); $('[name="clerkName"]').val(''); }); if($(".cascadeSelect").size() > 0){ var deptUserJson = $('[name="deptUserJson"]').val(); new CascadeSelect({"deptUserJson": eval(deptUserJson), needInit: true}); } });
init: function() { this.el = $('<span class="tag">'+ this.data.name +'<a class="tag-del">X</a></span>'); this.events(); return this.el; },
}).change(function(files){ $('#uploaderActiveImg').text('上传中...'); uploader.submit(); }).success(function(response) {
var SaveForm = function(){ var cookiename = $('[autosave="true"]').data('cookiename'); var val = JSON.stringify(Comm.serializeJson('[autosave="true"]')); $.cookie(cookiename, val,{path:'/'}); };
$(function(){ //表单验证 if ( $("[data-validate='true']").size() > 0 ) { require.async(['./validate_methods','ajaxform'], function(Validate) { new Validate.checked("[data-validate='true']",{ 'debug': false, //进行调试模式(表单不提交) 'errorElement' : 'label', //用什么标签标记错误 'errorClass' : "err", //指定错误提示的css类名 'ignore': null, //对某些元素不进行验证 'errorPlacement' : function (error, element) { //更改错误信息显示的位置 element.parent().find('.show-msg').html(error) }, 'success': function (label) {}, 'submitHandler': function(form){ //提交事件 var btn = $(form).find('[type="submit"]'); btn.removeAttr('disabled').removeClass('disabled'); $(form).ajaxSubmit({ 'dataType': 'json', 'timeout': 3000, 'error' : function(){ btn.attr('disabled',false).removeClass('disabled'); return Comm.alertTips({'msg' : '提交出错!'}) }, 'success': function(json) { var n = Number(json.status); var url = json.url; switch(n){ case 1: Comm.alertTips({'msg' : json.message}); if (url!='') { window.location.href=url; } else { setTimeout('location.reload();',2000); } break; default: btn.removeAttr('disabled').removeClass('disabled'); return Comm.alertTips({'msg' : json.message}) } } }).submit(function() {return false;}); } }) }) } /* * 自动补全 */ //邮箱 Comm.AutoEmail("[autoemail='true']",{ 'data' : gv.autoemail }); //行业 带默认选项 var AutoIndustry = $('#tags-industry'); if ( AutoIndustry.size() > 0 ) { require.async(['tagsedit'], function() { AutoIndustry.tagEditor({ autocomplete: { 'data': gv.URL.GetIndustry, 'async': true, 'ajaxDataType': 'xml' }, delimiter: ' ' }); $(document).on('click','.industry-tags a',function(){ var txt = $(this).text(); AutoIndustry.tagEditor('addTag', txt); }) }) } //通用自动补全方法 $(document).on('focus','[autocomplete="true"]',function(){ var that = $(this); require.async(['AutoComplete'], function() { that.AutoComplete({ 'data': that.data("complete-url"), 'ajaxDataType': 'xml', 'maxHeight': 300 }) }); }) /* * 上传头像 */ $(document).on('click','.edit-avatar',function(){ var $this = $(this), uid = $this.data('uid'); Comm.CropPhoto({ title:"上传头像", size:[160,160], data: { 'userid' : uid }, fileSize: "1024KB", success: function(url){ $this.find('img').attr('src',url); $this.find('input').val(url); } }) }); /* * 重新绑定手机号 * */ //注册 $('#SetPhone').one('click',function(){ $('#Phone').removeAttr('disabled').removeClass('disabled'); }); /* * 发送验证码 * */ // 倒计时 var wait = 60; var __time = function (o) { if (wait == 0) { o.addClass("btn-orange"); o.html("重新发送"); wait = 60; } else { o.removeClass('btn-orange'); o.html("重新发送(" + wait + ")"); wait--; setTimeout(function() { __time(o) }, 1000) } }; var __SendCode = function (that) { var phone = $("#Phone").val(); if ( !/^0?(13|15|18|17|14)[0-9]{9}$/.test(phone) ) { return Comm.alertTips({'msg' : '请输入正确的手机号!'}) } $.ajax({ cache: true, type: "POST", url: gv.URL.SendCode, data: {'phone':phone}, dataType: 'JSON', async: false, error: function() { return Comm.alertTips({'msg' : '发送失败,请稍后再试!!'}) }, success: function(data) { var status = Number(data.status); if ( status==1 ) { Comm.alertTips({'msg': data.message }); that.removeClass('btn-orange'); __time(that); } else { return Comm.alertTips({'msg' : data.message }) } } }); }; $(document).on('click','#SendCode',function(){ var that = $(this); if (that.hasClass('btn-orange')) { return __SendCode(that) } return false; }); /* * 表单输入框默认提示 * */ //静态数据 $(document).on('focus','[data-tips="true"]',function(){ var that = $(this), amount = that.data('amount'), types = that.data('types'); new Comm.TipsInput(that,{ 'data' : eval(types), 'Amount' : amount }); }); //动态数据 $(document).on('focus','[data-tips="ajax"]',function(){ var that = $(this), amount = that.data('amount'), equalto = $(that.data('equalto')).val(), url = that.data('url'), PostData = {"keyword":''}; if ( equalto != undefined || equalto != "") { PostData = {"keyword": equalto } } $.ajax({ type: "POST", url: url, data: PostData, dataType: "json", success: function(json){ if (json.status == 1) { new Comm.TipsInput(that,{ 'data' : json, 'Amount' : amount }); } } }); }); /* * 评分 */ new Comm.Raty('.star-scoring'); /* * 下拉选项 * */ if ($('select').size() > 0 ) { require.async(['selectbox'],function(selectbox){ selectbox($('select')); }) } /* * 表单自动保存 * */ if ($('[autosave="true"]').size() > 0 ) { require.async(['cookie'], function() { var SaveForm = function(){ var cookiename = $('[autosave="true"]').data('cookiename'); var val = JSON.stringify(Comm.serializeJson('[autosave="true"]')); $.cookie(cookiename, val,{path:'/'}); }; setInterval( SaveForm, 10000 ); }) } /* * 发私信 * */ $(document).on('click','.btn-send-letter',function(){ var that = $(this), data = { "uid": that.data('uid'), "name": that.data('name') }; require.async(['template','dialog','./validate_methods','ajaxform'], function(template,dialog,Validate,ajaxform) { var html = template('SendLetter', data); var _SendLetter = dialog({ title: '发私信给:' + data.name, content: html, width: '400' }).showModal(); new Validate.checked("#SendLetterForm",{ 'errorElement' : 'label', //用什么标签标记错误 'errorClass' : "err", //指定错误提示的css类名 'ignore': null, //对某些元素不进行验证 'errorPlacement' : function (error, element) { //更改错误信息显示的位置 element.parent().parent().find('.show-msg').html(error) }, 'success': function (label) {}, 'submitHandler': function(form){ //提交事件 var btn = $(form).find('[type="submit"]'); btn.removeAttr('disabled').removeClass('disabled'); $(form).ajaxSubmit({ 'dataType': 'json', 'timeout': 3000, 'error' : function(){ btn.attr('disabled',false).removeClass('disabled'); return Comm.alertTips({'msg' : '提交出错!'}) }, 'success': function(data) { var n = Number(data.status); switch(n){ case 1: _SendLetter.remove(); //关闭窗口 return Comm.alertTips({'msg' : data.message}); break; default: btn.removeAttr('disabled').removeClass('disabled'); return Comm.alertTips({'msg' : data.message}) } } }).submit(function() {return false;}); } }) }) }) });
$('a.delete').on('ajax:success', function () { $(this).closest('article').hide('normal'); });
$('#SetPhone').one('click',function(){ $('#Phone').removeAttr('disabled').removeClass('disabled'); });
}).bind('click',function(){ $(that.element).trigger('checkuse',[{active:true,silent:false}]); }).trigger('checkuse',[{active:true,silent:true,init:true}]);
$(that.element).closest('div.ui-checkbox').find('span.ui-icon').bind('click',function(){ $(that.element).trigger('click'); });
$('[name="clerkId"]').on('change', function(e){ var clerk = $(e.target); $('[name="clerkName"]').val(clerk.find('option:selected').text()); });
$('[name="deptId"]').on('change', function(e){ var dept = $(e.target); $('[name="deptName"]').val(dept.find('option:selected').text()); $('[name="trialName"]').val(''); $('[name="clerkName"]').val(''); });
$('[name="trialId"]').on('change', function(e){ var trialCourt = $(e.target); $('[name="trialName"]').val(trialCourt.find('option:selected').text()); });
$(".JS-trigger-more-information").on('click', function(e){ $("#court-more-information").removeClass("fn-hide"); //组件:滚动条 Scroller.use('.JS-need-scroller'); $(e.target).parent().remove(); });
$("#load-more-details").on('click', function(){ $("#more-details").removeClass("fn-hide"); Scroller.use('.JS-need-scroller'); $("#load-more-details").css("display","none"); });
parseElementFromTemplate: function() { this.element = $(this.get('template')); },
onUsed:function(params){ var that = this; that.used = true; $(that.element).prop('checked',true); $(that.element).closest('div.ui-checkbox').addClass('ui-checkbox-checked'); },
define(function(require, exports, module) { var $ = require('$'); var Position = require('../util/dom/position'); var Shim = require('../util/dom/iframe-shim'); var Widget = require('./widget'); // Overlay // ------- // Overlay 组件的核心特点是可定位(Positionable)和可层叠(Stackable) // 是一切悬浮类 UI 组件的基类 var Overlay = Widget.extend({ attrs: { // 基本属性 width: null, height: null, zIndex: 99, visible: false, // 定位配置 align: { // element 的定位点,默认为左上角 selfXY: [0, 0], // 基准定位元素,默认为当前可视区域 baseElement: Position.VIEWPORT, // 基准定位元素的定位点,默认为左上角 baseXY: [0, 0] }, // 父元素 parentNode: document.body }, show: function() { // 若从未渲染,则调用 render if(!this.rendered) { this.render(); } this.set('visible', true); return this; }, hide: function() { this.set('visible', false); return this; }, setup: function() { var that = this; // 加载 iframe 遮罩层并与 overlay 保持同步 this._setupShim(); // 窗口resize时,重新定位浮层 this._setupResize(); // 统一在显示之后重新设定位置 this.after('show', function() { that._setPosition(); }); }, destroy: function() { // 销毁两个静态数组中的实例 erase(this, Overlay.allOverlays); erase(this, Overlay.blurOverlays); return Overlay.superclass.destroy.call(this); }, // 进行定位 _setPosition: function(align) { // 不在文档流中,定位无效 if(!isInDocument(this.element[0])) { return; } align || (align = this.get('align')); // 如果align为空,表示不需要使用js对齐 if(!align) { return; } var isHidden = this.element.css('display') === 'none'; // 在定位时,为避免元素高度不定,先显示出来 if(isHidden) { this.element.css({ visibility: 'hidden', display: 'block' }); } Position.pin({ element: this.element, x: align.selfXY[0], y: align.selfXY[1] }, { element: align.baseElement, x: align.baseXY[0], y: align.baseXY[1] }); // 定位完成后,还原 if(isHidden) { this.element.css({ visibility: '', display: 'none' }); } return this; }, // 加载 iframe 遮罩层并与 overlay 保持同步 _setupShim: function() { var shim = new Shim(this.element); // 在隐藏和设置位置后,要重新定位 // 显示后会设置位置,所以不用绑定 shim.sync this.after('hide _setPosition', shim.sync, shim); // 除了 parentNode 之外的其他属性发生变化时,都触发 shim 同步 var attrs = ['width', 'height']; for(var attr in attrs) { if(attrs.hasOwnProperty(attr)) { this.on('change:' + attr, shim.sync, shim); } } // 在销魂自身前要销毁 shim this.before('destroy', shim.destroy, shim); }, // resize窗口时重新定位浮层,用这个方法收集所有浮层实例 _setupResize: function() { Overlay.allOverlays.push(this); }, // 除了 element 和 relativeElements,点击 body 后都会隐藏 element _blurHide: function(arr) { arr = $.makeArray(arr); arr.push(this.element); this._relativeElements = arr; Overlay.blurOverlays.push(this); }, // 用于 set 属性后的界面更新 _onRenderWidth: function(val) { this.element.css('width', val); }, _onRenderHeight: function(val) { this.element.css('height', val); }, _onRenderZIndex: function(val) { this.element.css('zIndex', val); }, _onRenderAlign: function(val) { this._setPosition(val); }, _onRenderVisible: function(val) { this.element[val ? 'show' : 'hide'](); } }); // 绑定 blur 隐藏事件 Overlay.blurOverlays = []; $(document).on('click', function(e) { hideBlurOverlays(e); }); // 绑定 resize 重新定位事件 var timeout; var winWidth = $(window).width(), winHeight = $(window).height(); Overlay.allOverlays = []; $(window).resize(function() { var winNewWidth = $(window).width(), winNewHeight = $(window).height(); // IE678 莫名其妙触发 resize // http://stackoverflow.com/questions/1852751/window-resize-event-firing-in-internet-explorer if(winWidth !== winNewWidth || winHeight !== winNewHeight) { timeout && clearTimeout(timeout); timeout = setTimeout(function() { $(Overlay.allOverlays).each(function(i, item) { // 当实例为空或隐藏时,不处理 if(!item || !item.get('visible')) { return; } item._setPosition(); }); }, 80); } winWidth = winNewWidth; winHeight = winNewHeight; }); module.exports = Overlay; // Helpers // ------- function isInDocument(element) { return $.contains(document.documentElement, element); } function hideBlurOverlays(e) { $(Overlay.blurOverlays).each(function(index, item) { // 当实例为空或隐藏时,不处理 if(!item || !item.get('visible')) { return; } // 遍历 _relativeElements ,当点击的元素落在这些元素上时,不处理 for(var i = 0; i < item._relativeElements.length; i++) { var el = $(item._relativeElements[i])[0]; if(el === e.target || $.contains(el, e.target)) { return; } } // 到这里,判断触发了元素的 blur 事件,隐藏元素 item.hide(); }); } // 从数组中删除对应元素 function erase(target, array) { for(var i = 0; i < array.length; i++) { if(target === array[i]) { array.splice(i, 1); return array; } } } });
onNotUsed:function(params){ var that = this; that.used = false; $(that.element).prop('checked',false); $(that.element).closest('div.ui-checkbox').removeClass('ui-checkbox-checked'); },
onBoardItemClick : function (e){ var item = e.currentTarget, id = $(item).data('id'); this.openBoard(id); },
getter: function(val) { return $(val).eq(0); }
require.async(['selectbox'],function(selectbox){ selectbox($('select')); })
ComposePopupView.prototype.onShow = function (sType, oMessageOrArray, aToEmails, sCustomSubject, sCustomPlainText) { kn.routeOff(); var self = this, sFrom = '', sTo = '', sCc = '', sDate = '', sSubject = '', oText = null, sText = '', sReplyTitle = '', aResplyAllParts = [], oExcludeEmail = {}, mEmail = Data.accountEmail(), sSignature = Data.signature(), bSignatureToAll = Data.signatureToAll(), aDownloads = [], aDraftInfo = null, oMessage = null, sComposeType = sType || Enums.ComposeType.Empty, fEmailArrayToStringLineHelper = function (aList, bFriendly) { var iIndex = 0, iLen = aList.length, aResult = [] ; for (; iIndex < iLen; iIndex++) { aResult.push(aList[iIndex].toLine(!!bFriendly)); } return aResult.join(', '); } ; oMessageOrArray = oMessageOrArray || null; if (oMessageOrArray && Utils.isNormal(oMessageOrArray)) { oMessage = Utils.isArray(oMessageOrArray) && 1 === oMessageOrArray.length ? oMessageOrArray[0] : (!Utils.isArray(oMessageOrArray) ? oMessageOrArray : null); } if (null !== mEmail) { oExcludeEmail[mEmail] = true; } this.currentIdentityID(this.findIdentityIdByMessage(sComposeType, oMessage)); this.reset(); if (Utils.isNonEmptyArray(aToEmails)) { this.to(fEmailArrayToStringLineHelper(aToEmails)); } if ('' !== sComposeType && oMessage) { sDate = oMessage.fullFormatDateValue(); sSubject = oMessage.subject(); aDraftInfo = oMessage.aDraftInfo; oText = $(oMessage.body).clone(); if (oText) { oText.find('blockquote.rl-bq-switcher').each(function () { $(this).removeClass('rl-bq-switcher hidden-bq'); }); oText.find('.rlBlockquoteSwitcher').each(function () { $(this).remove(); }); } oText.find('[data-html-editor-font-wrapper]').removeAttr('data-html-editor-font-wrapper'); sText = oText.html(); switch (sComposeType) { case Enums.ComposeType.Empty: break; case Enums.ComposeType.Reply: this.to(fEmailArrayToStringLineHelper(oMessage.replyEmails(oExcludeEmail))); this.subject(Utils.replySubjectAdd('Re', sSubject)); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw]; this.sInReplyTo = oMessage.sMessageId; this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences); break; case Enums.ComposeType.ReplyAll: aResplyAllParts = oMessage.replyAllEmails(oExcludeEmail); this.to(fEmailArrayToStringLineHelper(aResplyAllParts[0])); this.cc(fEmailArrayToStringLineHelper(aResplyAllParts[1])); this.subject(Utils.replySubjectAdd('Re', sSubject)); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = ['reply', oMessage.uid, oMessage.folderFullNameRaw]; this.sInReplyTo = oMessage.sMessageId; this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.references()); break; case Enums.ComposeType.Forward: this.subject(Utils.replySubjectAdd('Fwd', sSubject)); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw]; this.sInReplyTo = oMessage.sMessageId; this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences); break; case Enums.ComposeType.ForwardAsAttachment: this.subject(Utils.replySubjectAdd('Fwd', sSubject)); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = ['forward', oMessage.uid, oMessage.folderFullNameRaw]; this.sInReplyTo = oMessage.sMessageId; this.sReferences = Utils.trim(this.sInReplyTo + ' ' + oMessage.sReferences); break; case Enums.ComposeType.Draft: this.to(fEmailArrayToStringLineHelper(oMessage.to)); this.cc(fEmailArrayToStringLineHelper(oMessage.cc)); this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc)); this.bFromDraft = true; this.draftFolder(oMessage.folderFullNameRaw); this.draftUid(oMessage.uid); this.subject(sSubject); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null; this.sInReplyTo = oMessage.sInReplyTo; this.sReferences = oMessage.sReferences; break; case Enums.ComposeType.EditAsNew: this.to(fEmailArrayToStringLineHelper(oMessage.to)); this.cc(fEmailArrayToStringLineHelper(oMessage.cc)); this.bcc(fEmailArrayToStringLineHelper(oMessage.bcc)); this.subject(sSubject); this.prepearMessageAttachments(oMessage, sComposeType); this.aDraftInfo = Utils.isNonEmptyArray(aDraftInfo) && 3 === aDraftInfo.length ? aDraftInfo : null; this.sInReplyTo = oMessage.sInReplyTo; this.sReferences = oMessage.sReferences; break; } switch (sComposeType) { case Enums.ComposeType.Reply: case Enums.ComposeType.ReplyAll: sFrom = oMessage.fromToLine(false, true); sReplyTitle = Utils.i18n('COMPOSE/REPLY_MESSAGE_TITLE', { 'DATETIME': sDate, 'EMAIL': sFrom }); sText = '<br /><br />' + sReplyTitle + ':' + '<blockquote><p>' + sText + '</p></blockquote>'; break; case Enums.ComposeType.Forward: sFrom = oMessage.fromToLine(false, true); sTo = oMessage.toToLine(false, true); sCc = oMessage.ccToLine(false, true); sText = '<br /><br /><br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TITLE') + '<br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_FROM') + ': ' + sFrom + '<br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_TO') + ': ' + sTo + (0 < sCc.length ? '<br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_CC') + ': ' + sCc : '') + '<br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SENT') + ': ' + Utils.encodeHtml(sDate) + '<br />' + Utils.i18n('COMPOSE/FORWARD_MESSAGE_TOP_SUBJECT') + ': ' + Utils.encodeHtml(sSubject) + '<br /><br />' + sText; break; case Enums.ComposeType.ForwardAsAttachment: sText = ''; break; } if (bSignatureToAll && '' !== sSignature && Enums.ComposeType.EditAsNew !== sComposeType && Enums.ComposeType.Draft !== sComposeType) { sText = this.convertSignature(sSignature, fEmailArrayToStringLineHelper(oMessage.from, true), sText, sComposeType); } this.editor(function (oEditor) { oEditor.setHtml(sText, false); if (Enums.EditorDefaultType.PlainForced === Data.editorDefaultType() || (!oMessage.isHtml() && Enums.EditorDefaultType.HtmlForced !== Data.editorDefaultType())) { oEditor.modeToggle(false); } }); } else if (Enums.ComposeType.Empty === sComposeType) { this.subject(Utils.isNormal(sCustomSubject) ? '' + sCustomSubject : ''); sText = Utils.isNormal(sCustomPlainText) ? '' + sCustomPlainText : ''; if (bSignatureToAll && '' !== sSignature) { sText = this.convertSignature(sSignature, '', Utils.plainToHtml(sText, true), sComposeType); } this.editor(function (oEditor) { oEditor.setHtml(sText, false); if (Enums.EditorDefaultType.Html !== Data.editorDefaultType() && Enums.EditorDefaultType.HtmlForced !== Data.editorDefaultType()) { oEditor.modeToggle(false); } }); } else if (Utils.isNonEmptyArray(oMessageOrArray)) { _.each(oMessageOrArray, function (oMessage) { self.addMessageAsAttachment(oMessage); }); } aDownloads = this.getAttachmentsDownloadsForUpload(); if (Utils.isNonEmptyArray(aDownloads)) { Remote.messageUploadAttachments(function (sResult, oData) { if (Enums.StorageResultType.Success === sResult && oData && oData.Result) { var oAttachment = null, sTempName = '' ; if (!self.viewModelVisibility()) { for (sTempName in oData.Result) { if (oData.Result.hasOwnProperty(sTempName)) { oAttachment = self.getAttachmentById(oData.Result[sTempName]); if (oAttachment) { oAttachment.tempName(sTempName); } } } } } else { self.setMessageAttachmentFailedDowbloadText(); } }, aDownloads); } this.triggerForResize(); };
$(document).on('click','.industry-tags a',function(){ var txt = $(this).text(); AutoIndustry.tagEditor('addTag', txt); })
oText.find('blockquote.rl-bq-switcher').each(function () { $(this).removeClass('rl-bq-switcher hidden-bq'); });
'click [data-role=del]': function(e) { this._removeItem($(e.target).parent()); return false; },
oText.find('.rlBlockquoteSwitcher').each(function () { $(this).remove(); });
var ActiveEdit = function(options) { var authority = { tags: [1,2,3], price: [3], intro: [1,2,3,4], hImgId: [1,2,3,5] }; function indexOf(array, value) { return ~$.inArray(value, array); } var type, el, html, um, headImg={}, // 封面图片数据 {img_id: , img_url: }. allTags, // 所有标签,载入即保存. tagList = [], sellerData, checkItemValues = common.checkItemValues; el = $('<div></div>'); el.html($('#'+options.template).html()); function setTitle(title) { // 标题 el.find('#title').val(title); } function setIntro(intro) { // 简介 el.find('#intro').val(intro); } function setDetail(detail) { // 详情 el.find('#detail').val(detail); } function setPrice(price) { // 价格 el.find('#price').val(price); } var headImgStatus = { headImgUpload: el.find('#headImgUpload'), headImgWrap: el.find('#headImgWrap'), headImgUrl: el.find('#headImgUrl'), show: function(url) { this.headImgUpload.hide(); this.headImgWrap.show(); var img = '<img src='+ url +' alt="">'; this.headImgUrl.html(img); }, reset: function() { this.headImgUrl.html(''); this.headImgUpload.show(); this.headImgWrap.hide(); } } function createHeadImg(o){ // {img_url: , img_id: } headImg = o; headImgStatus.show(o.img_url); } function setHeadImgUrl(head_img_url) { // 首图 if (head_img_url) { createHeadImg({img_url: head_img_url}); } else { headImgStatus.reset(); } } function filterTags(tags) { var result = []; $.each(tags, function(i, tag){ if (tag.status == 0) { result.push(tag); } }) return result; } function getAllTags(fn) { // 获取所有标签 server.tags({page: 1, size: 50}, function(resp){ if (resp.code == 0) { fn(filterTags(resp.body.tags)); } else { tip(resp.msg || '获取标签失败'); } }) } function setDetailAll (detailAll) { // if (!um) { um = UE.getEditor('myEditor'); } um.ready(function(){ um.setContent(detailAll); }) } var Tag = function(tag) { this.data = tag; this.init(); } Tag.prototype = { constructor: Tag, init: function() { this.el = $('<span class="tag">'+ this.data.name +'<a class="tag-del">X</a></span>'); this.events(); return this.el; }, events: function() { var _this = this; this.el.on('click', '.tag-del', function(e){ _this.close(); removeTag(_this); e.stopPropagation(); }) }, close: function() { this.el.remove(); } } function createTag(tag) { var flag = true; if (tagList.length >=1) { tip('最多创建一个标签'); flag = false; } else { for (var i=0; i<tagList.length; i++) { if (tagList[i].data.id == tag.id) { tip('已经创建此标签'); flag = false; } } } if (flag) { var newTag = new Tag(tag); tagList.push(newTag); el.find('.ind-text').before(newTag.el); } } function removeTag(tag) { for (var i=tagList.length-1; i >= 0; i--) { if (tagList[i] == tag) tagList.splice(i, 1); } } function getTagData(tagName) { for (var i = 0; i<allTags.length; i++) { if (allTags[i].name == tagName) { return allTags[i]; } } } function setActTags(tags) { // 标签 if (!tags) return false; if ($.type(tags) == 'array') { if (tags.length) { for (var i=0; i < tags.length; i++) { createTag(getTagData(tags[i])); } } } else { createTag(getTagData(tags)); } } function clearTags() { if (tagList.length) { for(var i=0; i<tagList.length; i++) { tagList[i].close(); } } tagList = []; } function clear() { sellerData = ''; headImg = {}; clearTags(); } function init(type, datas) { clear(); if (type == 'edit') sellerData = datas; setTitle(datas && datas.title || ''); setDetailAll(datas && datas.detail || ''); if (indexOf(authority.hImgId, options.typeId)) { setHeadImgUrl(datas && datas.h_img_id); } if (indexOf(authority.tags, options.typeId)) { setActTags(datas && datas.tag_name || ''); } if (indexOf(authority.intro, options.typeId)) { setIntro(datas && datas.intro || ''); } if (indexOf(authority.price, options.typeId)) { setPrice(datas && datas.price || ''); } } function setHeadImgUpload() { // 上传背景图片 var uploader = new Uploader({ trigger: '#uploaderActiveImg', name: 'img', action: '/manager/managerUser/imgUp', accept: 'image/*', data: {'isReturnUrl': 1} }).change(function(files){ $('#uploaderActiveImg').text('上传中...'); uploader.submit(); }).success(function(response) { var response = $.parseJSON(response); if (response.code == 0) { createHeadImg(response.body); } else { tip(response.msg); } $('#uploaderActiveImg').text('选择图片'); }).error(function(file){ tip('上传封面图失败'); $('#uploaderActiveImg').text('选择图片'); }) } /** * get * */ function getValues(callback) { var title, intro, detail, headImgId, newsId, tagId; detail = UE.getEditor('myEditor').getContent(); (title = checkItemValues($('#title'), '活动标题不能为空')) && //(intro = checkItemValues($('#intro'), '活动简述不能为空')) && function(){ // 封面照片验证. if (!indexOf(authority.hImgId, options.typeId)) return true; if (type == 'create' && !headImg.img_id) { tip ('请上传封面照片'); return false; } else { return true; } }() && function(){ // 标签验证规则 if (!indexOf(authority.tags, options.typeId)) return true; if (!tagList.length) { tip ('必须添加标签'); return false; } else { tagId = tagList[0].data.id; return true; } }() && function(){ newsId = sellerData && sellerData.id || ''; var parms = { newsId: newsId, title: title, detail: detail }; if (indexOf(authority.hImgId, options.typeId)) { headImgId = headImg.img_id; parms.hImgId = headImgId; } if (indexOf(authority.tags, options.typeId)) { parms.tagId = tagId; } if (indexOf(authority.intro, options.typeId)) { parms.tagId = tagId; intro = $.trim($('#intro').val()); parms.intro = intro; } if (indexOf(authority.price, options.typeId)) { var price = $.trim($('#price').val()); parms.price = price; } callback(parms); }(); } el.find('#hImgReset').click(function(e){ headImgStatus.reset(); }) el.find('#tagsCon').on('click', '.ui-button-tag', function(e){ var target = $(e.target), id = target.attr('data-id'), name = target.text(); createTag({name: name, id: id}); }) el.find('#reset').click(function(){ // 重置 init('create'); }) el.find('#save').click(function(){ // 保存 getValues(function(o){ var parms = o; var dialog = wait(); if (type == 'create') { delete parms.newsId; parms.cityId = options.cityId; parms.typeId = options.typeId; server.addNews(parms, function(resp){ if (resp.code == 0) { dialog.destroy(); result.trigger('add', resp.body.news_id); } else { tip(resp.msg || '保存失败'); } }) } else if (type == 'edit') { !parms.headImgId && (delete parms.headImgId); parms.cityId = options.cityId; parms.typeId = options.typeId; server.updateNews(parms, function(resp){ dialog.destroy(); if (resp.code == 0) { result.trigger('save', sellerData.id); } else { tip(resp.msg || '保存失败'); } }) } }) }) var result = { load: function(typeway, datas, fn) { type = (typeway == 'edit' && typeway) || 'create'; var fn = ($.type(datas) == 'function') && datas; if (type == 'create') { init(type); $('#reset').show(); } else { init(type, datas); $('#reset').hide(); } }, init: function(fn) { fn && fn.call(null, el); if (indexOf(authority.hImgId, options.typeId)) { setHeadImgUpload(); } // setFileUpload(); if (indexOf(authority.tags, options.typeId)) { getAllTags(function(tags){ var content = ''; allTags = tags; for(var i=0; i<tags.length; i++) { content += '<a href="javascript:;" data-id='+ tags[i].id +' class="ui-button-tag ui-button ui-button-morange">'+ tags[i].name +'</a>'; } $('#tagsCon').html(content); }); } } } K.Observe.make(result); return result; }
define(function(require, exports, module) { var $ = require('$'); var single = {}; // 挂载ajax单例命名空间 var pool = {}; // 挂载ajax连接池命名空间 var config = { loginPage: '/', noPermissionAction: function() { location.href = config.loginPage; }, errorAction: function(xhr, status) { } }; var defaultRule = { /** * 默认判断成功的条件,默认是返回JSON并且其中具有code属性值200 */ success: function(data) { return data && (+data.code) === 200; }, /** * 默认判断无权限的条件,默认是返回JSON并且其中具有code属性值401 */ permission: function(data) { return data && (+data.code) === 401; } }; /** * * @param data 服务端返回值 * @param p {Object} ajax配置参数 * @param type {String} success/permission * @returns {boolean} */ var rule = function(data, p, type) { var fn; if(p && p.rule && $.isFunction(p.rule[type])) { fn = p.rule[type]; } else { fn = defaultRule[type]; } return fn(data) === true; }; $(document).keydown(function(e) { // 防止ESC键导致终端AJAX请求,这种情况下AJAX的状态值是error if(e.keyCode === 27) { return false; } }); if(!!window.ActiveXObject) { // IE清除ajax缓存 $.ajaxSetup({cache: false}); } var Ajax = { /** * 设置默认的成功判断规则 * @param callback */ setSuccessRule: function(callback) { defaultRule.success = function(data) { return callback(data); }; Ajax.setSuccessRule = null; }, /** * 设置默认的无权限判断规则 * @param callback */ setPermissionRule: function(callback) { defaultRule.permission = function(data) { return callback(data); }; Ajax.setPermissionRule = null; }, /** * 设置无权限时候的默认动作,该方法只能用一次 * @param callback */ setNoPermissionAction: function(callback) { config.noPermissionAction = callback; Ajax.setNoPermissionAction = null; }, /** * 设置失败时候的默认动作,该方法只能用一次 * @param callback */ setErrorAction: function(callback) { config.errorAction = callback; Ajax.setErrorAction = null; }, /** * 基类ajax,要求服务端返回的结果格式必须是JSON,建议按code,data格式返回,如: * { * code: 状态码,一般就以下三个:200成功/400失败/401无权限 * data: 返回的数据源 * } * 如果规则不是这样,可以使用 setSuccessRule 和 setPermissionRule 来设置,其他的表示失败 * @param {Object} params * 在ajax的参数基础上增加了 * rule.success: 判定服务端成功的条件,优先级高于默认设定,默认data.code === 200 * rule.permission: 判定服务端无权限的条件,优先级高于默认设定,默认data.code === 401 * permission: 无权限时候的回调函数 * @return {Object} XMLHttpRequrest对象 */ base: function(params) { var obj = $.extend({}, params || {}); if(!obj.before || (obj.before && obj.before() !== false)) { obj.dataType = 'json'; obj.type = params.type || 'GET'; obj.success = function(data) { if(rule(data, obj, 'success')) { // 成功 if(params.success) { params.success(data); } } else if(rule(data, obj, 'permission')) { // 无权限 $.isFunction(params.permission) ? params.permission(data) : config.noPermissionAction(); } else { // 服务端判定失败 $.isFunction(params.error) ? params.error(data) : config.errorAction(data); } }; obj.error = function(xhr, status) { if(status !== 'abort') { // 主动放弃,这种一般是程序控制,不应该抛出error $.isFunction(params.error) ? params.error(xhr, status) : config.errorAction(xhr, status); } }; obj.complete = function(xhr, status) { if($.isFunction(params.complete)) { params.complete(xhr, status); } }; return $.ajax(obj); } }, /** * AJAX单例模式: * 如果请求资源和上一次相同,则放弃后来的请求 * 如果请求资源和上一次不同,则中断之前的请求,使用后面的请求 * @param {String} name 单例命名空间 * @return {Object} 返回对创建的单例的操作方法:发起请求send,放弃请求abort */ single: function(name) { if(!single[name]) { single[name] = {}; } var actions = { /** * 发起一个AJAX单例请求 * @param params 同base方法的参数 * @return {undefined} */ send: function(params) { var flag = single[name].url && (params.url === single[name].url); if(flag) { // 请求URL相同 if(typeof params.data === typeof single[name].data && typeof params.data === 'object') { for(var i in params.data) { if(params.data[i] !== single[name].data[i]) { // 请求的数据也相同,则认为是发起同一个请求 flag = false; break; } } } else { flag = params.data === single[name].data; } } if(flag) { // 请求的URL和参数相同则保留上一个 return false; } else { // 不相同则放弃前一个请求 if(single[name].xhr) { single[name].xhr.abort(); } } var completeFn = params.complete; params.complete = function(xhr, status) { single[name] = {}; // 完成后清理 if($.isFunction(completeFn)) { completeFn(xhr, status); } }; single[name] = { xhr: Ajax.base(params), url: params.url, data: params.data }; }, /** * 放弃单例AJAX请求 */ abort: function() { if(single[name] && single[name].xhr && single[name].xhr.readyState !== 4) { single[name].xhr.abort(); single[name].xhr = null; } } }; return actions; }, /** * 构建ajax连接池,存放在pool中,pool结构如下: * { * poolName: { * 1: [], * 2: [], * ... * priority: [] * } * } * @param {String} name 连接池名称 * @param {Integer} max 最大并发数 * @param {Integer} priority 有多少个优先级(最高优先级为1,往后优先级越低) * @return {Object} 返回对创建的连接池的操作方法:增加连接,放弃连接 */ pool: function(name, max, priority) { if(!pool[name]) { // 连接池未建立 var n = 0; // 当前连接数量 pool[name] = {}; // 存放连接 var list = pool[name]; max = Math.max(1, parseInt(max, 10) || 1); priority = Math.max(1, parseInt(priority, 10) || 1); for(var i = 1; i <= priority; i++) { list[i] = []; } /* * 发送请求,并在请求结束后处理队列 */ var activeXHR = {}; var send = function() { if(n < max) { for(var i = 1; i <= priority; i++) { if(list[i].length > 0) { var obj = list[i].shift(); if(obj) { var xhrId = +new Date() + '_' + Math.random(); var completeFn = obj.complete; n++; obj.complete = (function(xhrId) { return function(xhr, status) { n--; if(status !== 'success') { xhr && xhr.abort(); } if($.isFunction(completeFn)) { completeFn(xhr, status); } activeXHR[xhrId] = null; delete activeXHR[xhrId]; send(); // 递归,执行下一个请求 }; })(xhrId); activeXHR[xhrId] = Ajax.base(obj); break; } } } } }; var actions = { /** * 给连接池增加一个连接 * @param {Object} params 同base方法的参数 * @param {Integer} p 优先级 * @return {Undefined} */ add: function(params, p) { if(p && list[p]) { list[p].push(params); } else { // 不在定义优先级范围内或不提供优先级,当作优先级最低 list[priority].push(params); } send(); }, /** * 放弃连接池中所有AJAX请求,并清空该连接池 */ abort: function() { if(list) { for(var i = 1; i <= priority; i++) { list[i].length = 0; } for(var objId in activeXHR) { activeXHR[objId].abort(); } } } }; return actions; } } }; module.exports = Ajax; });
}).error(function(file){ tip('上传封面图失败'); $('#uploaderActiveImg').text('选择图片'); })
update: function(oElement, fValueAccessor) { $(oElement).text(JSON.stringify(ko.unwrap(fValueAccessor()))); }