diff options
Diffstat (limited to 'umc-iui/src/main/resources/webroot/umc-fm/js')
7 files changed, 7381 insertions, 0 deletions
diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/CommonUtil.js b/umc-iui/src/main/resources/webroot/umc-fm/js/CommonUtil.js new file mode 100644 index 00000000..1d6144dd --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/CommonUtil.js @@ -0,0 +1,42 @@ +var commonUtil = {};
+commonUtil.arrayRemove = function (aryInstance, index) {
+ if (aryInstance == undefined || aryInstance == null) {
+ return;
+ }
+ for (var i = 0, n = 0; i < aryInstance.length; i++) {
+ if (aryInstance[i] != aryInstance[dx]) {
+ aryInstance[n++] = aryInstance[i];
+ }
+ }
+ aryInstance.length -= 1;
+};
+
+//对Date的扩展,将 Date 转化为指定格式的String
+// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
+// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
+// 例子:
+// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
+// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
+commonUtil.parseDate = function (dateObj, format) {
+ var o = {
+ "M+": dateObj.getMonth() + 1, //month
+ "d+": dateObj.getDate(), //day
+ "h+": dateObj.getHours(), //hour
+ "m+": dateObj.getMinutes(), //minute
+ "s+": dateObj.getSeconds(), //second
+ "q+": Math.floor((dateObj.getMonth() + 3) / 3), //quarter
+ "S": dateObj.getMilliseconds() //millisecond
+ }
+ if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
+ (dateObj.getFullYear() + "").substr(4 - RegExp.$1.length));
+ for (var k in o)
+ if (new RegExp("(" + k + ")").test(format))
+ format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] :
+ ("00" + o[k]).substr(("" + o[k]).length));
+ return format;
+};
+
+commonUtil.strToJson = function (str) {
+ var json = eval('(' + str + ')');
+ return json;
+}
\ No newline at end of file diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/alarmConds.js b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmConds.js new file mode 100644 index 00000000..77f4d4ab --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmConds.js @@ -0,0 +1,261 @@ +var AlarmConds = function () {
+
+ return {
+
+ parseActiveConds2JSon: function (conds) {
+ return this.parseConds2JSon(conds, 1);
+ },
+ parseHistoryConds2JSon: function (conds) {
+ return this.parseConds2JSon(conds, 2);
+ },
+
+ /**
+ * 传入的条件数组说明:
+ * 每个条件都是一个对象,包含2个属性:type和data。type表示条件的类型,data是一个数组,每项都表示一个条件。
+ * 下面是支持的所有条件的说明:
+ * 1)网元
+ * {
+ * type : 'Position',
+ * data : [{ //支持多个
+ * locationId : 'lId1',
+ * oid : 'oid1',
+ * isSelf : true //是否分组,true表示只包含自己,false表示分组
+ * }
+ * ]
+ * }
+ * 2)级别
+ * {
+ * type : 'Severity',
+ * data : [{ //支持多个
+ * severity : 1 //1表示严重,2表示主要,3表示次要,4表示警告
+ * }
+ * ]
+ * }
+ * 3)确认状态
+ * {
+ * type : 'AckState',
+ * data : [{ //支持多个
+ * ackState : 1 //1表示已确认,2表示未确认
+ * }
+ * ]
+ * }
+ * 4)可见性
+ * {
+ * type : 'FilterState',
+ * data : [{ //支持多个
+ * filterState : 1 //1表示可见,0表示不可见
+ * }
+ * ]
+ * }
+ * 5)告警类型
+ * {
+ * type : 'AlarmType',
+ * data : [{ //支持多个
+ * alarmType : 1 //0表示通信告警,1表示处理错误告警,2表示服务质量告警,3表示设备告警,4表示环境告警,5表示网管系统告警,6表示完整性告警,7表示可用性告警,8表示物理攻击告警,9表示安全攻击告警,10表示时限告警
+ * }
+ * ]
+ * }
+ * 6)告警码
+ * {
+ * type : 'ProbableCause',
+ * data : [{ //支持多个
+ * systemType : 6,
+ * code : 1001
+ * }
+ * ]
+ * }
+ * 7)发生时间
+ * {
+ * type : 'RaisedTime',
+ * data : [{ //支持一个
+ * mode : 0, //0表示区间,1表示最近
+ * start : 1399429229000, //mode为0时,表示开始时间,mode为1时,表示时间的毫秒值
+ * end : 1399515601000 //mode为0时,表示结束时间,mode为1时,表示时间的毫秒值
+ * }
+ * ]
+ * }
+ * 8)确认时间
+ * {
+ * type : 'AckTime',
+ * data : [{ //支持一个
+ * mode : 0, //0表示区间,1表示最近
+ * start : 1399429229000, //mode为0时,表示开始时间,mode为1时,表示时间的毫秒值
+ * end : 1399515601000 //mode为0时,表示结束时间,mode为1时,表示时间的毫秒值
+ * }
+ * ]
+ * }
+ * 9)清除时间
+ * {
+ * type : 'ClearedTime',
+ * data : [{ //支持一个
+ * mode : 0, //0表示区间,1表示最近
+ * start : 1399429229000, //mode为0时,表示开始时间,mode为1时,表示时间的毫秒值
+ * end : 1399515601000 //mode为0时,表示结束时间,mode为1时,表示时间的毫秒值
+ * }
+ * ]
+ * }
+ * 10)告警ID
+ * {
+ * type : 'AlarmId',
+ * data : [{ //支持一个
+ * id : 1412923648983
+ * }
+ * ]
+ * }
+ * 11)MOC
+ * {
+ * type : 'Moc',
+ * data : [{ //支持一个
+ * moc : 'moc' //支持前缀匹配,如:'moc%'
+ * }
+ * ]
+ * }
+ * 12)ip地址
+ * {
+ * type : 'NeIp',
+ * data : [{ //支持一个
+ * neIp : '10.74.165.57'
+ * }
+ * ]
+ * }
+ */
+ parseConds2JSon: function (conds, ruleType) {
+ var parser = {
+ Position: function (cond) {
+ var condStr = "";
+ if (cond.type === "Position" && cond.data.length > 0) {
+ condStr = "<NewPositionCond OwnerType='Position' value='" + cond.data[0].locationId + "#" + cond.data[0].oid + "#" + cond.data[0].isSelf;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "∷" + cond.data[i].locationId + "#" + cond.data[i].oid + "#" + cond.data[i].isSelf;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ Severity: function (cond) {
+ var condStr = "";
+ if (cond.type === "Severity" && cond.data.length > 0) {
+ condStr = "<PerceivedSeverity value='" + cond.data[0].severity;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "," + cond.data[i].severity;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ AckState: function (cond) {
+ var condStr = "";
+ if (cond.type === "AckState" && cond.data.length > 0) {
+ condStr = "<AckState value='" + cond.data[0].ackState;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "," + cond.data[i].ackState;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ FilterState: function (cond) {
+ var condStr = "";
+ if (cond.type === "FilterState" && cond.data.length > 0) {
+ condStr = "<FilterState value='" + cond.data[0].filterState;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "," + cond.data[i].filterState;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ AlarmType: function (cond) {
+ var condStr = "";
+ if (cond.type === "AlarmType" && cond.data.length > 0) {
+ condStr = "<AlarmType value='" + cond.data[0].alarmType;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "," + cond.data[i].alarmType;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ ProbableCause: function (cond) {
+ var condStr = "";
+ if (cond.type === "ProbableCause" && cond.data.length > 0) {
+ condStr = "<ProbableCause value='" + cond.data[0].systemType + "#" + cond.data[0].code;
+ for (var i = 1; i < cond.data.length; i++) {
+ condStr += "," + cond.data[i].systemType + "#" + cond.data[i].code;
+ }
+ condStr += "' />";
+ }
+ return condStr;
+ },
+ RaisedTime: function (cond) {
+ var condStr = "";
+ if (cond.type === "RaisedTime" && cond.data.length === 1) {
+ condStr = "<RaisedTime model='" + cond.data[0].mode + "' start='" + cond.data[0].start + "' end= '" + cond.data[0].end + "' queryTimeZone='' condTimeZone='' />";
+ }
+ return condStr;
+ },
+ AckTime: function (cond) {
+ var condStr = "";
+ if (cond.type === "AckTime" && cond.data.length === 1) {
+ condStr = "<AckTime model='" + cond.data[0].mode + "' start='" + cond.data[0].start + "' end= '" + cond.data[0].end + "' queryTimeZone='' condTimeZone='' />";
+ }
+ return condStr;
+ },
+ ClearedTime: function (cond) {
+ var condStr = "";
+ if (cond.type === "ClearedTime" && cond.data.length === 1) {
+ condStr = "<ClearedTime model='" + cond.data[0].mode + "' start='" + cond.data[0].start + "' end= '" + cond.data[0].end + "' queryTimeZone='' condTimeZone='' />";
+ }
+ return condStr;
+ },
+ AlarmId: function (cond) {
+ var condStr = "";
+ if (cond.type === "AlarmId" && cond.data.length === 1) {
+ condStr = "<IDString value='" + cond.data[0].id + "'/>";
+ }
+ return condStr;
+ },
+ Moc: function (cond) {
+ var condStr = "";
+ if (cond.type === "Moc" && cond.data.length === 1) {
+ condStr = "<Moc Moc='" + cond.data[0].moc + "' SELECT_MODEL='false' MocSelf='true' />";
+ }
+ return condStr;
+ },
+ NeIp: function (cond) {
+ var condStr = "";
+ if (cond.type === "NeIp" && cond.data.length === 1) {
+ condStr = "<NeIp value='" + cond.data[0].neIp + "' />";
+ }
+ return condStr;
+ }
+ };
+
+ var d = new Date();
+ var JSonObj = {
+ rule: {
+ ruleId: -1,
+ name: "Alarm",
+ creator: "admin",
+ createTime: d.getTime(),
+ modifier: "",
+ modifyTime: 0,
+ description: "",
+ state: true,
+ ruleType: ruleType,
+ ruleSort: 1,
+ owner: "",
+ attrs: "<Attrs/>"
+ }
+ };
+ var condStr = "<CompoundCond>";
+ for (var i = 0; i < conds.length; i++) {
+ condStr += parser[conds[i].type](conds[i]);
+ }
+ JSonObj.rule.ruleData = condStr + "</CompoundCond>";
+ //return JSON.stringify(JSonObj);
+ return JSonObj;
+ }
+
+ };
+}();
\ No newline at end of file diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsServerPageTable.js b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsServerPageTable.js new file mode 100644 index 00000000..c00c6664 --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsServerPageTable.js @@ -0,0 +1,514 @@ +var serverPageTable = {};
+var queryCacheId = null;
+var alarmCount;
+/* Bootstrap style full number pagination control */
+$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings) {
+ return {
+ "iEnd": oSettings.fnDisplayEnd(),
+ "iLength": oSettings._iDisplayLength,
+ "iTotal": oSettings.fnRecordsTotal(),
+ "iFilteredTotal": oSettings.fnRecordsDisplay(),
+ "iPage": Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
+ "iTotalPages": Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
+ };
+};
+
+$.extend($.fn.dataTableExt.oPagination, {
+ "bootstrap_extended": {
+ "fnInit": function (oSettings, nPaging, fnDraw) {
+ var oLang = oSettings.oLanguage.oPaginate;
+ var oPaging = oSettings.oInstance.fnPagingInfo();
+
+ var fnClickHandler = function (e) {
+ e.preventDefault();
+ if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
+ fnDraw(oSettings);
+ }
+ };
+
+ $(nPaging).append(
+ '<div class="pagination-panel"> ' + oLang.sPage + ' ' +
+ '<a href="#" class="btn btn-sm default prev disabled" title="' + oLang.sPrevious + '"><i class="fa fa-angle-left"></i></a>' +
+ '<input type="text" class="pagination-panel-input input-mini input-inline input-sm" maxlenght="5" style="text-align:center; margin: 0 4px; border: 1px solid rgb(169, 169, 169);height: 28px;">' +
+ '<a href="#" class="btn btn-sm default next disabled" title="' + oLang.sNext + '"><i class="fa fa-angle-right"></i></a> ' +
+ oLang.sPageOf + ' <span class="pagination-panel-total"></span>' +
+ '</div>'
+ );
+
+ var els = $('a', nPaging);
+
+ $(els[0]).bind('click.DT', {action: "previous"}, fnClickHandler);
+ $(els[1]).bind('click.DT', {action: "next"}, fnClickHandler);
+
+ $('.pagination-panel-input', nPaging).bind('change.DT', function (e) {
+ var oPaging = oSettings.oInstance.fnPagingInfo();
+ e.preventDefault();
+ var page = parseInt($(this).val());
+ if (page > 0 && page < oPaging.iTotalPages) {
+ if (oSettings.oApi._fnPageChange(oSettings, page - 1)) {
+ fnDraw(oSettings);
+ }
+ } else {
+ $(this).val(oPaging.iPage + 1);
+ }
+ });
+
+ $('.pagination-panel-input', nPaging).bind('keypress.DT', function (e) {
+ var oPaging = oSettings.oInstance.fnPagingInfo();
+ if (e.which == 13) {
+ var page = parseInt($(this).val());
+ if (page > 0 && page < oSettings.oInstance.fnPagingInfo().iTotalPages) {
+ if (oSettings.oApi._fnPageChange(oSettings, page - 1)) {
+ fnDraw(oSettings);
+ }
+ } else {
+ $(this).val(oPaging.iPage + 1);
+ }
+ e.preventDefault();
+ }
+ });
+ },
+
+ "fnUpdate": function (oSettings, fnDraw) {
+ var iListLength = 5;
+ var oPaging = oSettings.oInstance.fnPagingInfo();
+ var an = oSettings.aanFeatures.p;
+ var i, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);
+
+ if (oPaging.iTotalPages < iListLength) {
+ iStart = 1;
+ iEnd = oPaging.iTotalPages;
+ }
+ else if (oPaging.iPage <= iHalf) {
+ iStart = 1;
+ iEnd = iListLength;
+ } else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
+ iStart = oPaging.iTotalPages - iListLength + 1;
+ iEnd = oPaging.iTotalPages;
+ } else {
+ iStart = oPaging.iPage - iHalf + 1;
+ iEnd = iStart + iListLength - 1;
+ }
+
+
+ for (i = 0, iLen = an.length; i < iLen; i++) {
+ var wrapper = $(an[i]).parents(".dataTables_wrapper");
+
+ if (oPaging.iTotalPages <= 0) {
+ $('.pagination-panel, .dataTables_length', wrapper).hide();
+ } else {
+ $('.pagination-panel, .dataTables_length', wrapper).show();
+ }
+
+ $('.pagination-panel-total', an[i]).html(oPaging.iTotalPages);
+ $('.pagination-panel-input', an[i]).val(oPaging.iPage + 1);
+
+ // Remove the middle elements
+ $('li:gt(1)', an[i]).filter(':not(.next)').remove();
+
+ // Add the new list items and their event handlers
+ for (j = iStart; j <= iEnd; j++) {
+ sClass = (j == oPaging.iPage + 1) ? 'class="active"' : '';
+ $('<li ' + sClass + '><a href="#">' + j + '</a></li>')
+ .insertBefore($('li.next:first', an[i])[0])
+ .bind('click', function (e) {
+ e.preventDefault();
+ oSettings._iDisplayStart = (parseInt($('a', this).text(), 10) - 1) * oPaging.iLength;
+ fnDraw(oSettings);
+ });
+ }
+
+ // Add / remove disabled classes from the static elements
+ if (oPaging.iPage === 0) {
+ $('a.prev', an[i]).addClass('disabled');
+ } else {
+ $('a.prev', an[i]).removeClass('disabled');
+ }
+
+ if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
+ $('a.next', an[i]).addClass('disabled');
+ } else {
+ $('a.next', an[i]).removeClass('disabled');
+ }
+ }
+ }
+ }
+});
+
+//构造查询条件
+serverPageTable.getRestPara = function (cond, tableSetting) {
+
+ var conditions = {};
+ //告警级别
+ if (cond.severity != null && cond.severity != "undefined" && cond.severity.length > 0) {
+ var severity = '['+cond.severity+']';
+ var severityObj = window.JSON.parse(severity);
+ conditions.severities=severityObj;
+ }
+
+ //确认状态
+ if (cond.ackState != null && cond.ackState != "undefined" && cond.ackState.length > 0) {
+ var ackState = '[' + cond.ackState + ']';
+ var ackStateObj = window.JSON.parse(ackState)
+ conditions.ackStates=ackStateObj;
+ }
+
+ //可见性
+ if (cond.filterState != null && cond.filterState != "undefined" && cond.filterState.length > 0) {
+ var filterState = '[' + cond.filterState + ']';
+ var filterStateObj = window.JSON.parse(filterState);
+ conditions.isVisibles=filterStateObj;
+ }
+
+ //告警确认时间
+ if (cond.ackTimeMode != null && cond.ackTimeMode != "undefined") {
+ var ackTime;
+ if(cond.ackTimeMode === 1){
+ ackTime = '{"timeMode": '+cond.ackTimeMode+',"relativeTime": '+cond.ackRelativeTime+'}';
+ }else{
+ ackTime = '{"beginTime": '+cond.ackTimeStarTime+',"endTime": '+cond.ackTimeEndTime+',"timeMode": '+cond.ackTimeMode+'}';
+ }
+ var ackTimeObj = window.JSON.parse(ackTime);
+ conditions.ackTime = ackTimeObj;
+ }
+
+ //告警发生时间
+ if (cond.alarmRaisedTimeMode != null && cond.alarmRaisedTimeMode != "undefined") {
+ var alarmRaisedTime;
+ if(cond.alarmRaisedTimeMode === 1){
+ alarmRaisedTime = '{"timeMode": '+cond.alarmRaisedTimeMode+',"relativeTime": '+cond.alarmRaisedRelativeTime+'}';
+ }else{
+ alarmRaisedTime = '{"beginTime": '+cond.alarmRaisedStartTime+',"endTime": '+cond.alarmRaisedEndTime+',"timeMode": '+cond.alarmRaisedTimeMode+'}';
+ }
+ var alarmRaisedTimeObj = window.JSON.parse(alarmRaisedTime);
+ conditions.alarmRaisedTime = alarmRaisedTimeObj;
+ }
+
+ //告警清除时间
+ if (cond.clearedTimeMode != null && cond.clearedTimeMode != "undefined") {
+ var clearedTime;
+ if(cond.clearedTimeMode === 1){
+ clearedTime = '{"timeMode": '+cond.clearedTimeMode+',"relativeTime": '+cond.clearedTimeRelativeTime+'}';
+ }else{
+ clearedTime = '{"beginTime": '+cond.clearedTimeStartTime+',"endTime": '+cond.clearedTimeEndTime+',"timeMode": '+cond.clearedTimeMode+'}';
+ }
+ var clearedTimeTimeObj = window.JSON.parse(clearedTime);
+ conditions.alarmClearedTime = clearedTimeTimeObj;
+ }
+
+ //告警码
+ if (cond.probableCause != null && cond.probableCause != "undefined") {
+ //var probableCauseArr = cond.probableCause.split(',');
+ var str = "";
+ var arr="[";
+ for (var i = 0; i < cond.probableCause.length; i++) {
+ if(i === 0){
+ if(cond.probableCause[i].type === "1"){
+ arr+='{"systemType":'+cond.probableCause[i].codeid+',"codes":[]}';
+ }else{
+ arr+='{"systemType":'+cond.probableCause[i].parentid+',"codes":['+cond.probableCause[i].codeid+']}';
+ }
+ }else{
+ if(cond.probableCause[i].type === "1"){
+ arr+=',{"systemType":'+cond.probableCause[i].codeid+',"codes":[]}';
+ }else{
+ arr+=',{"systemType":'+cond.probableCause[i].parentid+',"codes":['+cond.probableCause[i].codeid+']}';
+ }
+ }
+ }
+ arr+="]";
+ var probableCausesObj = window.JSON.parse(arr);
+ conditions.probableCauses = probableCausesObj;
+ }
+
+ var requests={};
+ requests.condition=conditions;
+ requests.pageSize=tableSetting._iDisplayLength;
+ requests.pageNumber=tableSetting._iDisplayStart / tableSetting._iDisplayLength + 1;
+ if(cond.alarmType===2 && requests.pageNumber === 1){
+ requests.queryCacheId="";
+ }else if(cond.alarmType===2 && requests.pageNumber != 1){
+ requests.queryCacheId=queryCacheId;
+ }
+
+ var resStr = window.JSON.stringify(requests);
+ result={
+ request:resStr
+ };
+ return result;
+};
+
+
+serverPageTable.initDataTable = function (setting, cond, divId) {
+ //转换colomn
+ var column = setting.columns;
+ var setting;
+ //先把原来的表格清空
+ $('#' + divId).children().remove();
+ var tableId = setting.tableId;
+ var tableEleStr = '<table class="table table-striped table-bordered table-hover" id= ' + tableId + '>'
+ + '<thead>'
+ + '<tr role="row" class="heading" >'
+ + '</tr>'
+ + '</thead>'
+ + '<tbody>'
+ + '</tbody>'
+ + '</table>';
+ $('#' + divId).append(tableEleStr);
+ //$('#'+ tableId).append(' <thead><tr role="row" class="heading" ></tr></thead><tbody></tbody>');
+ var trEle = $('#' + tableId + ' > thead >tr');
+ //var dataTableColumn = [];
+ for (var one in column) {
+ if (one != "contains") {
+ var th = '<th>' + column[one].name + '</th>';
+ trEle.append(th);
+ }
+ }
+
+ var table = $("#" + tableId).dataTable({
+ //"sDom" : "tr<'row'<'col-md-6 col-sm-12'><'col-md-6 col-sm-12'pli>>", // datatable layout
+ // "sDom" : "<'row'<'col-md-12 col-sm-12'lip>r><'table-scrollable't>>",
+ "oLanguage": setting.language,//汉化
+ "bJQueryUI": true,
+ "bPaginate": true,// 分页按钮
+ "bFilter": false,// 搜索栏
+ "bAutoWidth": true,//自动设置列宽
+ "bLengthChange": true,// 每行显示记录数
+ "iDisplayLength": 10,// 每页显示行数
+ "bSort": false,// 排序
+ "bInfo": true,// Showing 1 to 10 of 23 entries 总记录数没也显示多少等信息
+ "bWidth": true,
+ "bScrollCollapse": false,
+ "sScrollY": "400px",
+ "sScrollX": "100%",
+ "sPaginationType": "bootstrap_extended", // 分页, bootstrap_extended 一共两种样式 另一种为two_button // 是datatables默认
+ "bProcessing": true,
+ "bServerSide": true,
+ "bDestroy": true,
+ "bSortCellsTop": true,
+ "sDom": '<"top"rt><"bottom"lip>',
+ "sAjaxSource": setting.restUrl,// ./js/testJson.json setting.restUrl
+ "aoColumns": setting.columns,
+ "bRetrieve": true,
+ "fnServerData": function (sSource, aoData, fnCallback, oSettings) {
+ oSettings.jqXHR = $.ajax({
+ "type": 'get',
+ "url": sSource,
+ "dataType": "json",
+ "data": serverPageTable.getRestPara(cond, oSettings),
+ "success": function (resp) {
+ oSettings.iDraw = oSettings.iDraw + 1;
+
+ var data = {};
+ if(cond.ruleType===1){
+ var logList = resp.alarms;
+ data.iTotalRecords = resp.totalCount;
+ data.iTotalDisplayRecords = resp.totalCount;
+
+ }else if(cond.ruleType===2){
+ var logList = resp.alarms;
+ if(resp.queryCacheId === ""){
+ data.iTotalRecords = alarmCount;
+ data.iTotalDisplayRecords = alarmCount;
+ }else{
+ alarmCount = resp.totalCount;
+ data.iTotalRecords = resp.totalCount;
+ data.iTotalDisplayRecords = resp.totalCount;
+ queryCacheId = resp.queryCacheId;
+ }
+
+ }
+
+ var pageInfo = null;
+ setting=oSettings;
+ if (pageInfo != null) {
+ vm.logInfo[vm.logType].pageInfo = pageInfo;
+ }
+
+ //添加序号
+ for(var i=0;i<logList.length;i++){
+ logList[i].order="<a>"+(i+1)+"</a>";
+ }
+ //组合告警码
+ for(var i=0;i<logList.length;i++){
+ logList[i].probableCauseCodeNameAndCode=logList[i].probableCauseCodeName+"("+logList[i].probableCauseCode+")";
+ }
+
+ data.aaData = logList;
+ data.sEcho = oSettings;
+ fnCallback(data);
+
+ $('#dataTableCheckBox').click(function () {
+ var checkArr = $('#' + divId + ' .details-check input[type="checkbox"]');//
+ for (var i = 0; i < checkArr.length; i++) {
+ if ($(checkArr).eq(i).attr('id') != 'dataTableCheckBox') {
+ if ($('#dataTableCheckBox').prop("checked")) {
+ $(checkArr).eq(i).removeClass('checked');
+ $(checkArr).eq(i).prop('checked',true);
+ } else {
+ $(checkArr).eq(i).addClass('checked');
+ $(checkArr).eq(i).prop('checked',false);
+ }
+ }
+ }
+ });
+ }
+
+ });
+ },
+ "fnDrawCallback": function( oSettings ) { // run some code on table redraw
+
+ var tableWrapper = $('div.dataTables_wrapper');
+ //自适应对齐表头
+ var $tableHead = $('div.dataTables_scrollHeadInner > table.dataTable', tableWrapper);
+ var tbodyHead = $('tbody', $tableHead);
+ if(tbodyHead && tbodyHead.length >0){
+ $(tbodyHead).remove();
+ }
+
+ var $tableBody = $('table#' + tableId, tableWrapper);
+ var trIn = $('thead > tr:nth-child(1)', $tableHead);
+ var trBodyHead = $('thead > tr:nth-child(1)', $tableBody);
+ var tds = $(trIn).children();
+ var ths = $(trBodyHead).children();
+ for(var k=0;k<tds.length;k++){
+ $(ths.eq(k)).html('<div style="height: 0;overflow: hidden;">' + tds.eq(k).html() + '</div>');
+ }
+ var bodyRows = $('tbody > tr', $tableBody);
+ for(var i=0;i<bodyRows.length;i++){
+ var rowClone = $(bodyRows.eq(i)).clone();
+ var tds = $(rowClone).children();
+ for(var j=0;j<tds.length;j++){
+ $(tds.eq(j)).html('<div style="height: 0;overflow: hidden;">' + tds.eq(j).html() + '</div>');
+ $(tds.eq(j)).height('0px');
+ $(tds.eq(j)).css('padding-top','0px');
+ $(tds.eq(j)).css('padding-bottom','0px');
+ $(tds.eq(j)).css('border-top-width','0px');
+ $(tds.eq(j)).css('border-bottom-width','0px');
+ }
+ $(rowClone).height('0px');
+ $tableHead.append($(rowClone).prop("outerHTML"));
+ }
+
+ $('div.dataTables_scrollBody', tableWrapper).css('width','100%');
+ //$('div.dataTables_scrollHead', tableWrapper).css('width','98.5%');
+ $('div.dataTables_scrollHeadInner', tableWrapper).css('padding-right', 0);
+
+ //$("table.dataTable > thead > tr > th:nth-child(2)", $(".dataTables_scrollHeadInner")).click();
+
+ //设置表格本体高度
+ //$('div.dataTables_scrollBody', tableWrapper).css('height', "280px");
+ //填充表头右边界
+ /* $('div.dataTables_scrollHead', tableWrapper).css('display','inline-block');
+ $("div.dataTables_scrollHead", tableWrapper).after("<div id='divRightPadding' style='overflow: hidden; background:#eee; position: relative; float:right; border: 1px solid #ddd; height:" + 42 + "px; width: 1.4%;'></div>"); */
+ /* if($.browser.mozilla){
+ $('div#divRightPadding', tableWrapper).css('height', '40');
+ } */
+ }
+ });
+
+ $(window).bind('resize', function () {
+ //oTable.DataTable.models.oSettings.bAjaxDataGet = false;
+ table.fnAdjustColumnSizing(setting);
+ } );
+
+ function format_Detail(oTable, nTr) {
+ var aData = oTable.fnGetData(nTr);
+
+ var sOut = '<table class = "detailTable" width="100%">';
+ sOut += '<tr><td class = "detailTitleStyle" width = 160><span class = "label label-primary">' + column[3].name + '</span></td><td class = "detailCellStyle" width = 320>' + null2space(aData[column[3].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle" width = 160><span class = "label label-primary">' + column[8].name + '</span></td><td class = "detailCellStyle" width = 320>' + null2space(vm.alTypes[aData[column[8].mData]]) + '</td></tr>';
+
+ sOut += '<tr><td class = "detailTitleStyle" width = 80><span class = "label label-primary">' + column[9].name + '</span></td><td class = "detailCellStyle" width = 160>' + null2space(aData[column[9].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle" width = 80><span class = "label label-primary">' + column[7].name + '</span></td><td class = "detailCellStyle" width = 160>' + null2space(aData[column[7].mData]) + '</td></tr>';
+
+ sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[6].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[6].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[11].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[11].mData]) + '</td></tr>';
+
+ sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[10].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[10].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[13].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[13].mData]) + '</td></tr>';
+
+ sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[12].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[12].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[5].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[5].mData]) + '</td></tr>';
+
+ sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[23].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[23].mData]) + '</td>';
+ sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[4].name + '</span></td><td class = "detailCellStyle">' + null2space(aData[column[4].mData]) + '</td></tr>';
+ // sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[5].name + '</span></td><td class = "detailCellStyle">' + aData[column[5].mData] + '</td></tr>';
+
+ // sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[4].name + '</span></td><td class = "detailCellStyle">' + aData[column[4].mData] + '</td>';
+ // sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[22].name + '</span></td><td class = "detailCellStyle">' + aData[column[22].mData] + '</td></tr>';
+ // sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[22].name + '</span></td><td class = "detailCellStyle">' + aData[column[22].mData] + '</td></tr>';
+
+ // sOut += '<tr><td class = "detailTitleStyle"><span class = "label label-primary">' + column[12].name + '</span></td><td class = "detailCellStyle">' + aData[column[12].mData] + '</td>';
+ // sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[17].name + '</span></td><td class = "detailCellStyle">' + aData[column[17].mData] + '</td></tr>';
+
+ sOut += '<td class = "detailTitleStyle"><span class = "label label-primary">' + column[16].name + '</span></td><td class = "detailCellStyle" colspan = 3>' + null2space(aData.additionalText) + '</td></tr>';
+
+ return sOut;
+ }
+ function null2space(nullStr){
+ if(nullStr == null){
+ return "";
+ } else {
+ return nullStr;
+ }
+ }
+ $('#' + tableId + '>tbody').on('click', 'td.details-control', function () {
+ var tr = $(this).closest('tr');
+ //var nTr = $(this).parents('tr')[0];
+ //var row = table.row( tr );
+ if (table.fnIsOpen(tr[0])) {
+ table.fnClose(tr[0]);
+ //if ( row.child.isShown() ) {
+ // This row is already open - close it
+ //row.child.hide();
+ tr.removeClass('shown');
+ }
+ else {
+ // Open this row
+ table.fnOpen(tr[0], format_Detail(table, tr[0]), 'details');
+ //row.child( format_Detail(row.data()) ).show();
+ tr.addClass('shown');
+ }
+ });
+
+ // mod by chenhao 2015-10-26 注释掉
+ // // 所有td注册一个点击事件用来展示出详情。
+ // $('#ict_alarms_table >tbody').on('click', 'td', function () {
+
+ // var className= $(this).eq(0).attr('class');
+ // //当点击的是如下的table页的时候
+ // if(className &&(className.indexOf('relInfo')>-1 || className.indexOf('details-check')>-1 || className.indexOf('ackState')>-1 || className.indexOf('details-control')>-1)){
+ // $('#right-menu').fadeOut();
+ // }else{
+ // //填充table的数据
+ // var tbody=$('#ict_table_general >tbody');
+ // tbody.children().remove();
+ // var trHtml="";
+ // var tr = $(this).closest('tr');
+ // var aData = table.fnGetData(tr[0]);
+ // for (var i = 0; i < column.length; i++) {
+ // if( column[i].bVisible == false ){//如果列可见就继续遍历下一个
+ // trHtml += '<tr role="row"><td>'+column[i].name+':</td><td>' + aData[column[i].mData] + '</td></tr>';
+ // }
+ // }
+ // tbody.append(trHtml);
+ // if(!vm.alarmId ||vm.alarmId==aData.alarmId){
+ // $('#right-menu').fadeToggle();
+ // }else{
+ // $('#right-menu').fadeIn();
+ // }
+ // vm.alarmId=aData.alarmId;
+ // }
+ // });
+ //重新调节列宽以适应window resize
+ $(window).bind('resize', function () {
+ //oTable.fnAdjustColumnSizing();
+ $("table.dataTable > thead > tr > th:nth-child(2)", $(".dataTables_scrollHeadInner")).click();
+ } );
+
+};
+
+
+
+
diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsUtil.js b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsUtil.js new file mode 100644 index 00000000..bd8231d2 --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/alarmsUtil.js @@ -0,0 +1,1154 @@ +var alarmsUtil = {};
+var alarmTemp=[];
+
+alarmsUtil.timeRender = function (obj) {
+ if (obj.aData[obj.mDataProp] == -1 || obj.aData[obj.mDataProp] == 0) {
+ return "";
+ } else {
+ var date = new Date(obj.aData[obj.mDataProp]);
+ return commonUtil.parseDate(date, 'yyyy-MM-dd hh:mm:ss');
+ }
+};
+
+alarmsUtil.LinkRender = function (obj) {
+ return '<a href="">' + obj.aData[obj.mDataProp] + '</a>';
+};
+
+alarmsUtil.ackState = function (obj) {
+
+ var innerHtml = "";
+ var ackState = obj.aData.ackState;
+ var alarmId = obj.aData.id;
+ var alarmIdArr = [alarmId];
+ var tableId="\'" + obj.oSettings.sTableId + "\'";
+ var divId="\'" + obj.oSettings.nTableWrapper.parentElement.id + "\'";
+ if (ackState == "1" && vm.ruleType == 1) {
+ innerHtml = "<a class=\"label label-sm label-info\" onclick=\" alarmsUtil.unaffirm([" + alarmIdArr + "]," + tableId + "," + divId + ","+obj.iDataRow+") \">Acknowledge</a>";
+ } else if(ackState == "1" && vm.ruleType == 2){
+ innerHtml = "<div class=\"label label-sm label-info\">Acknowledge</div>";
+ } else if(ackState == "2" ){
+ innerHtml = "<a class=\"label label-sm acknow-purple\" onclick=\" alarmsUtil.affirm([" + alarmIdArr + "]," + tableId + "," + divId + ","+obj.iDataRow+")\">Unacknowledge</a>";
+ }
+ return innerHtml;
+};
+
+alarmsUtil.Severity = function (obj) {
+
+ var innerHtml = "";
+ var Severity = obj.aData.perceivedSeverity;
+ if (Severity == "1") {
+ innerHtml = "<span style=\"color:#E24949 \" class=\"ict-alarm \" ></span><sapn \">Critical</sapn>";
+ } else if (Severity == "2") {
+ innerHtml = "<span style=\"color:#E59313 \" class=\"ict-alarm\" ></span><sapn \">Major</sapn>";
+ } else if (Severity == "3") {
+ innerHtml = "<span style=\"color:#F7E51B \" class=\"ict-alarm\" ></span><sapn \">Minor</sapn>";
+ } else if (Severity == "4") {
+ innerHtml = "<span style=\"color:#61C2DE \" class=\"ict-alarm\" ></span><sapn \">Warning</sapn>";
+ }
+ return innerHtml;
+
+};
+
+alarmsUtil.operate = function (obj) {
+
+ var alarmId = obj.aData.alarmId;
+ return "<div class='row col-xs-12'><div><a href='#' class=\"btn-xs grey btn-editable\" onclick=\" alarmsUtil.congfirms('" + alarmId + "')\"><i class=\"ict-delete\"></i>清除</a></div></div>";
+
+};
+
+alarmsUtil.congfirms = function (alarmId) {
+
+ bootbox.confirm('你确定要删除该告警吗?', function (result) { //你确定要删除该用户吗?
+
+ if (result) {
+ var sSource = "/web/rest/web/fm/curalarms?data={\"alarmId\":" + alarmId + "}&_dataSource=isc_PageRestDataSource_0&isc_metaDataPrefix=_&isc_dataFormat=json&_operationType=remove&_componentId=isc_com_zte_ums_aos_fm_view_eventview_table_AlarmTable_0";
+ $.ajax({
+ dataType : "json",
+ type : "DELETE",
+ //数据格式:[tab标签id,tabItem的名字,图片路径,tabItem的描述,更多的LInk地址]
+ contentType : 'application/json; charset=utf-8',
+ url : sSource,
+ data : null,
+ async : false,
+ success : function (msg) {
+ setTimeout(function () {
+ refreshByCond();
+ }, 500);
+ }
+ });
+ }
+
+ });
+
+};
+
+alarmsUtil.allOperate = function (obj) {
+
+ var record = obj.aData;
+ var hasModify = commonUtil.hasRigth('uep.pfl.sm.updateuser');
+ var hasDel = commonUtil.hasRigth('uep.pfl.sm.deluser');
+ var selectUsername = new String(record.userName);
+ var innerHtml = "";
+
+ // 如果有权限,显示操作列
+ if (hasModify) {
+ if (hasDel && selectUsername != "admin") {
+ innerHtml = "<div class='row col-xs-12'><div class='col-xs-6 modify_user'><a class=\"btn-xs grey btn-editable\" href='#' onclick=\"vm.modifyUser('" + selectUsername + "')\"><i class=\"ict-modify\"></i>修改</a></div><div class='col-xs-6'><a href='#' class=\"btn-xs grey btn-editable\" onclick=\"smUtil.congfirms('" + selectUsername + "')\"><i class=\"ict-delete\"></i>删除</a></div></div>";
+ } else {
+ innerHtml = "<div class='row col-xs-12'><div class='col-xs-6 modify_user'><a class=\"btn-xs grey btn-editable\" href='#' onclick=\"vm.modifyUser('" + selectUsername + "')\"><i class=\"ict-modify\"></i>修改</a></div>";
+ }
+ }
+
+ return innerHtml;
+
+};
+
+alarmsUtil.refresh = function () {
+
+ refreshByCond();
+
+}
+
+/*
+
+1.确认
+
+2.反确认
+
+ */
+
+alarmsUtil.loopAffirm = function (type) {
+
+ var checkArr = $('#ict_alarms_table_div .details-check input[type="checkbox"]');
+ var aidArr = [];
+ for (var i = 0; i < checkArr.length; i++) {
+ if($(checkArr[i]).prop("checked")){
+ if ($(checkArr[i]).attr('alarmId') != 'undefined' && $(checkArr[i]).attr('alarmId') != null) {
+ aidArr.push($(checkArr[i]).attr('alarmId'));
+ }
+ }
+ }
+
+ if (type == "1" && aidArr.length > 0) {
+ alarmsUtil.affirm(aidArr);
+ } else if (type == "2" && aidArr.length > 0) {
+ alarmsUtil.unaffirm(aidArr);
+ }
+
+}
+
+/*
+
+
+
+ */
+
+alarmsUtil.loopDelAralms = function () {
+
+ var checkArr = $('#ict_alarms_table_div .details-check input[type="checkbox"]');
+ var aidArr = [];
+ for (var i = 0; i < checkArr.length; i++) {
+ if($(checkArr[i]).prop("checked")){
+ if ($(checkArr[i]).attr('alarmId') != 'undefined' && $(checkArr[i]).attr('alarmId') != null) {
+ aidArr.push($(checkArr[i]).attr('alarmId'));
+ }
+ }
+ }
+
+ if (aidArr.length > 0) {
+ bootbox.confirm('Are you sure to delete alarm(s)', function (result) {
+ if (result) {
+ var sSource = "/api/umcfm/v1/curalarms?request={\"ids\":["+ aidArr +"]}";
+ $.ajax({
+ type : "DELETE",
+ dataType : "json",
+ contentType : 'application/json; charset=utf-8',
+ url : sSource,
+ data : null,
+ async : false,
+ success : function (msg) {
+ setTimeout(function () {
+ refreshByCond()
+ }, 500);
+ }
+ });
+ }
+ });
+ }
+}
+
+alarmsUtil.affirm = function (alarmIdArr,tableId,divId) {
+
+ var getData = {};
+ var request = {};
+ request.ids=[];
+ for(i=0;i<alarmIdArr.length;i++){
+ request.ids.push(alarmIdArr[i]);
+ }
+ var url = "";
+ if (vm.ruleType == 1) { //当前告警
+ request.ackState=1;
+ getData.request = JSON.stringify(request);
+ url = "/api/umcfm/v1/curalarms";
+ } else { //历史告警
+ url = "/ngict/rest/fm/hisalarms"
+ }
+
+ $.ajax({
+ type : "PUT",
+ contentType : 'application/json; charset=utf-8',
+ url : url + "?" + "request=" + JSON.stringify(request),
+ async : false,
+ success : function (msg) {
+ setTimeout(function () {
+ refreshByCond(tableId,divId);
+ }, 100);
+ },
+ error : function(msg){
+ setTimeout(function () {
+ refreshByCond(tableId,divId);
+ }, 100);
+ }
+ });
+
+}
+
+alarmsUtil.unaffirm = function (alarmIdArr,tableId,divId) {
+
+ var getData = {};
+ var request = {};
+ request.ids=[];
+ for(i=0;i<alarmIdArr.length;i++){
+ request.ids.push(alarmIdArr[i]);
+ }
+ request.ackState=2;
+ getData.request = JSON.stringify(request);
+ var url = "";
+ if (vm.ruleType == 1) { //当前告警
+ url = "/api/umcfm/v1/curalarms";
+ $.ajax({
+ "type" : "PUT",
+ "contentType" : 'application/json; charset=utf-8',
+ "url" : url + "?request=" + JSON.stringify(request),
+ async : false,
+ success : function (msg) {
+ setTimeout(function () {
+ refreshByCond(tableId,divId);
+ }, 100);
+ },
+ error : function(msg){
+ setTimeout(function () {
+ refreshByCond(tableId,divId);
+ }, 100);
+ }
+ });
+ }
+
+
+
+}
+
+alarmsUtil.checkBox = function (obj) {
+
+ var alarmId = obj.aData.id;
+ var innerHtml = '<input type="checkbox" alarmId="' + alarmId + '"/> ';
+ return innerHtml;
+}
+
+//初始化告警码树
+alarmsUtil.initProbableCausesTree = function () {
+ //zTree设置
+ var setting = {
+ view : {
+ selectedMulti : false, //设置是否可以同时选中多个借点。
+ showIcon : true, //不显示图标
+ showLine : false, //是否显示节点之间的连线
+ },
+ data : {
+ simpleData : {
+ enable : true //如果设置为 true,请务必设置 setting.data.simpleData 内的其他参数: idKey / pIdKey / rootPId,并且让数据满足父子关系。
+ }
+ },
+ callback : {
+ onExpand : zTreeOnExpand, //每次节点展开后触发的事件。
+ onCollapse : zTreeOnCollapse,
+ //onClick: zTreeOnClick
+ }
+ };
+ var probableCausesNodes;
+
+ //获取告警码树数据
+ getProbableCausesTreeNodes("");
+ //创建告警码树
+ $.fn.zTree.init($("#probableCausesTree"), setting, probableCausesNodes);
+ //获取所有现有的tree节点
+ var treeObj = $.fn.zTree.getZTreeObj("probableCausesTree");
+ initDataAtTree();
+ function initDataAtTree(){
+ getAllNodesWithoutTypeEqual2("")
+ };
+
+ function getAllNodesWithoutTypeEqual2(parentId){
+ var treeNodes=treeObj.getNodesByParam("parentId", parentId, null);
+ for(var i=0;i<treeNodes.length;i++){
+ if(treeNodes[i].type===0){
+ getProbableCausesTreeNodes(treeNodes[i].id);
+ addNodesToTree(treeNodes[i],"probableCausesTree");
+ getAllNodesWithoutTypeEqual2(treeNodes[i].id);
+ }
+ }
+ }
+
+ function zTreeOnExpand(event, treeId, treeNode) {
+ var childrenNodes = treeNode.children;
+ if (!childrenNodes) { //当没有子节点的时候才加载,否则会重复加载。
+ getProbableCausesTreeNodes(treeNode.id);
+ addNodesToTree(treeNode,treeId);
+ }
+ };
+
+ function addNodesToTree(treeNode, treeId) {
+ var obj = $.fn.zTree.getZTreeObj(treeId);
+ var node=obj.getNodeByParam("id", treeNode.id, null)
+ obj.addNodes(node, probableCausesNodes);
+ };
+
+ function zTreeOnCollapse(event, treeId, treeNode) {};
+
+ //告警信息中的type为0、1是父节点,2为子节点
+ function isParentNode(type) {
+ if (type != 2)
+ return true;
+ else
+ return false;
+ };
+
+ function constructProblemCauseName(node){
+ if(node.type===0){
+ return node.desc;
+ }else{
+ return node.desc + "(" + node.value + ")";
+ }
+ }
+
+ function getProbableCausesTreeNodes(alarmCodeParentId) {
+ probableCausesNodes = new Array();
+ var getData = {};
+ var request = {};
+ request.parentId = alarmCodeParentId;
+ getData.request = JSON.stringify(request);
+ $.ajax({
+ async : false,
+ "dataType" : 'json',
+ "type" : "GET",
+ "url" : "/api/umcfm/v1/probablecausestree",
+ "data" : getData,
+ "contentType" : 'application/json; charset=utf-8',
+ "success" : function (res, textStatus, jqXHR) {
+ var nodes = res;
+ chkDisabled = false;
+ if (nodes) {
+ for (var i = 0; i < nodes.length; i++) {
+ probableCausesNodes.push({
+ id : nodes[i].id,
+ pId : nodes[i].parentId,
+ name : constructProblemCauseName(nodes[i]),
+ chkDisabled : false,
+ isParent : isParentNode(nodes[i].type),
+ parentId : alarmCodeParentId,//treenode节点
+ codeId : nodes[i].value,
+ type : nodes[i].type
+ });
+ }
+ }
+ },
+ "error" : function () {}
+ });
+ }
+}
+
+//初始化位置树
+alarmsUtil.initDeptTree = function () {
+ //zTree设置
+ var setting = {
+ view : {
+ selectedMulti : false, //设置是否可以同时选中多个借点。
+ showIcon : true, //不显示图标
+ showLine : false, //是否显示节点之间的连线
+ },
+ data : {
+ simpleData : {
+ enable : true //如果设置为 true,请务必设置 setting.data.simpleData 内的其他参数: idKey / pIdKey / rootPId,并且让数据满足父子关系。
+ }
+ },
+ callback : {
+ onExpand : zTreeOnExpand, //每次节点展开后触发的事件。
+ onCollapse : zTreeOnCollapse,
+ //onClick: zTreeOnClick
+ }
+ };
+ var zNodes = [];
+ initDeptTree();
+ function initDeptTree() {
+ zNodes.push({
+ id:"VDU",
+ name:"VDU",
+ isParent:true
+ },
+ {
+ id:"HOST",
+ name:"HOST",
+ isParent:true
+ });
+ $.fn.zTree.init($("#deptTree"), setting, zNodes);
+ zNodes=[];
+ }
+ function getDeptTreeNode(alarmCodeParentId) {
+ if(alarmCodeParentId === "VDU"){
+ url="/api/roc/v1/resource/vdus";
+ }else if(alarmCodeParentId === "HOST"){
+ url="/api/roc/v1/resource/hosts";
+ }
+ $.ajax({
+ async : false,
+ "dataType" : 'json',
+ "type" : "GET",
+ "url" : url,
+ "contentType" : 'application/json; charset=utf-8',
+ "success" : function (res, textStatus, jqXHR) {
+ var nodes = res.data;
+ if (nodes) {
+ for (var i = 0; i < nodes.length; i++) {
+ zNodes.push({
+ id : nodes[i].oid,
+ parentId : alarmCodeParentId,//treenode节点
+ name : nodes[i].name,
+ isParent : false,
+ oid:nodes[i].oid
+ });
+ }
+ }
+ },
+ "error" : function () {}
+ });
+ }
+ function zTreeOnExpand(event, treeId, treeNode) {
+ getDeptTreeNode(treeNode.id);
+ addNodesToTree(treeNode,treeId);
+ zNodes=[];
+ };
+ function addNodesToTree(treeNode, treeId) {
+ var obj = $.fn.zTree.getZTreeObj(treeId);
+ var node=obj.getNodeByParam("id", treeNode.id, null)
+ obj.addNodes(node, zNodes);
+ };
+ function zTreeOnCollapse(event, treeId, treeNode) {};
+}
+
+//初始化所有的树
+alarmsUtil.initTree = function () {
+ //初始化告警码树和告警位置树
+ alarmsUtil.initProbableCausesTree();
+ alarmsUtil.initDeptTree();
+
+ function initFormData(ruleType) {
+
+ $("#confirmAction").hide();
+ $("#filterType").hide();
+ $("#action").hide();
+ if (ruleType == "alarmFilter") {
+ $("#filterType").show();
+ } else if (ruleType == "ack") {
+ $("#confirmAction").show();
+ } else if (ruleType == "forward") {
+ $("#action").show();
+ }
+
+ }
+
+ function getNumbers(rule) {
+
+ for (var i = 0; i < textValues.length; i++) {
+ rule[textValues[i]] = $("input[name='" + textValues[i] + "']").val();
+ }
+
+ }
+
+ function getCheckboxs(rule) {
+
+ for (var i = 0; i < else_checkboxNames.length; i++) {
+ rule[else_checkboxNames[i]] = $("input[name='" + else_checkboxNames[i] + "']").parent().hasClass('checked');
+ }
+ for (var item in checkboxNames_pair_spinnerIds) {
+ rule[item] = $('#' + checkboxNames_pair_spinnerIds[item]).val();
+ }
+ }
+
+ function setCheckboxs(rule) {
+
+ for (var item in checkboxNames_pair_spinnerIds) {
+ var value = 0;
+ if (rule != "") {
+ value = rule[item];
+ }
+ $('#' + item).val(value);
+ setSpinnerIsEnable(item, value);
+ }
+ for (var i = 0; i < else_checkboxNames.length; i++) {
+ $("input[name='" + else_checkboxNames[i] + "']").parent().iCheck(rule[else_checkboxNames[i]] ? 'check' : 'uncheck');
+ }
+ }
+}
+
+alarmsUtil.moveNode = function (item) {
+ if (item.hasClass("ict-arrowRight")) {
+ alarmsUtil.rightNode(item);
+ } else if (item.hasClass("ict-arrowLeft")) {
+ alarmsUtil.leftNode(item);
+ } else {
+ alarmsUtil.removeAll(item);
+ }
+}
+
+/*树添加信息到右侧的功能*/
+
+alarmsUtil.rightNode = function (item) {
+
+ var selecedNodeIds = [];
+ var treeType = item.attr('treeType');
+ var obj = $.fn.zTree.getZTreeObj(treeType);
+ var treeNodes = obj.getSelectedNodes();
+ var $table;
+
+ if (treeType == "deptTree") {
+ var $tds = $("#selectedDeptTreeTable td");
+ $table = $("#selectedDeptTreeTable");
+ for (var i = 0; i < $tds.length; i++) {
+ selecedNodeIds.push($tds.eq(i).attr('nodeid'));
+ }
+ } else if (treeType == "probableCausesTree") {
+ var $tds = $("#selectedProbableCausesTreeTable td");
+ $table = $("#selectedProbableCausesTreeTable");
+ for (var i = 0; i < $tds.length; i++) {
+ var systemTypeAndProbableCause={};
+ systemTypeAndProbableCause.codeId=$tds.eq(i).attr('codeId');
+ systemTypeAndProbableCause.parentid=$tds.eq(i).attr('parentid');
+ systemTypeAndProbableCause.type=$tds.eq(i).attr('type');
+ selecedNodeIds.push(systemTypeAndProbableCause);
+ }
+ }
+
+ //树上被选中的元素
+ for (var i = 0; i < treeNodes.length; i++) {
+
+ var htmlStr = "";
+ var text = treeNodes[i].name;
+ var id = treeNodes[i].id;
+ var codeId = treeNodes[i].codeId;
+ var type;
+ var parentId;
+ if (treeType == "deptTree") {
+ var oid = treeNodes[i].oid;
+ htmlStr = "<tr><td nodeId=" + id + " oid=" + oid + " >" + text + "</td></tr>";
+ } else if (treeType == "probableCausesTree") {
+
+ parentId = treeNodes[i].parentId;
+ type = treeNodes[i].type;
+ htmlStr = "<tr><td codeId=" + codeId + " parentId=" + parentId + " type=" + type + " >" + text + "</td></tr>";
+ }
+
+ if(treeType == "probableCausesTree"){
+ if(treeNodes[i].type === 2){
+ for(i=0;i<selecedNodeIds.length;i++){
+ if(selecedNodeIds[i].codeId === codeId || selecedNodeIds[i].codeId === parentId){
+ bootbox.alert("此节点(子树)或其父子树已经被添加!", function () {});
+ return;
+ }
+ }
+ }else if(treeNodes[i].type === 1){
+ $('#selectedProbableCausesTreeTable [parentid='+codeId+']').remove();
+ for(i=0;i<selecedNodeIds.length;i++){
+ if(selecedNodeIds[i].codeId === codeId ){
+ bootbox.alert("此节点(子树)或其父子树已经被添加!", function () {});
+ return;
+ }
+ }
+ }else if(treeNodes[i].type === 0){
+ bootbox.alert("不支持添加MOC", function () {});
+ break;
+ }
+ }
+
+ $table.append(htmlStr);
+
+ }
+
+ $('#selectedDeptTreeTable td').on("click", function () {
+
+ //获得所有选择的td
+ var $tds = $('#selectedDeptTree td');
+ //遍历改变样式
+ for (var i = 0; i < $tds.length; i++) {
+ $tds.eq(i).removeClass('tallCellSelected');
+ $tds.eq(i).parent().removeClass('checked');
+ }
+ //当前td设为选中
+ $(this).addClass('tallCellSelected');
+ $(this).parent().addClass("checked"); //tr 添加一个 checked 样式。
+ });
+
+ $('#selectedProbableCausesTreeTable td').on("click", function () {
+
+ //获得所有选择的td
+ var $tds = $('#selectedProbableCausesTreeTable td');
+ //遍历改变样式
+ for (var i = 0; i < $tds.length; i++) {
+ $tds.eq(i).removeClass('tallCellSelected');
+ $tds.eq(i).parent().removeClass('checked');
+ }
+ //当前td设为选中
+ $(this).addClass('tallCellSelected');
+ $(this).parent().addClass("checked"); //tr 添加一个 checked 样式。
+ });
+
+}
+
+
+
+alarmsUtil.leftNode = function (item) {
+
+ var treeType = item.attr('treeType');
+ if (treeType == "deptTree") {
+ $('#selectedDeptTreeTable').children().children(".checked").remove();
+ } else if (treeType == "probableCausesTree") {
+ $('#selectedProbableCausesTreeTable').children().children(".checked").remove();
+ }
+
+}
+
+alarmsUtil.removeAll = function (item) {
+
+ var treeType = item.attr('treeType');
+ if (treeType == "deptTree") { //如果是资源树
+ $('#selectedDeptTreeTable').children().remove();
+ } else if (treeType == "probableCausesTree") {
+ $('#selectedProbableCausesTreeTable').children().remove();
+ }
+}
+
+
+
+
+
+//调用datarangepicker组件 datarange 初始化
+
+alarmsUtil.setDateRange = function (dataRangeId, vm) {
+
+ var open = 'right';
+ var optionSet1 = {
+ startDate : "2015-08-02",
+ endDate : "2015-08-03",
+ format : 'YYYY-MM-DD h:mm A',
+ dateLimit : {
+ days : 180
+ },
+ showWeekNumbers : false,
+ timePicker : true,
+ timePickerIncrement : 5,
+ opens : open,
+ separator : ' - ',
+ locale : {
+ applyLabel : $.i18n.prop('ngict_fm_iui_curalarm_ok'),
+ cancelLabel : $.i18n.prop('ngict_fm_iui_curalarm_cancel'),
+ fromLabel : $.i18n.prop('ngict_fm_iui_curalarm_from'),
+ toLabel : $.i18n.prop('ngict_fm_iui_curalarm_to'),
+ daysOfWeek : [
+ $.i18n.prop('ngict_fm_iui_curalarm_Sun'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Mon'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Tues'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Wed'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Thurs'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Fri'),
+ $.i18n.prop('ngict_fm_iui_curalarm_Sat')
+ ],
+ monthNames : [$.i18n.prop('ngict_fm_iui_curalarm_January'), $.i18n.prop('ngict_fm_iui_curalarm_February'), $.i18n.prop('ngict_fm_iui_curalarm_March'), $.i18n.prop('ngict_fm_iui_curalarm_April'), $.i18n.prop('ngict_fm_iui_curalarm_May'), $.i18n.prop('ngict_fm_iui_curalarm_June'), $.i18n.prop('ngict_fm_iui_curalarm_July'), $.i18n.prop('ngict_fm_iui_curalarm_August'), $.i18n.prop('ngict_fm_iui_curalarm_September'), $.i18n.prop('ngict_fm_iui_curalarm_October'), $.i18n.prop('ngict_fm_iui_curalarm_November'), $.i18n.prop('ngict_fm_iui_curalarm_December')],
+ firstDay : 1
+ }
+ };
+
+ //datarangepicker确认
+ $('input[id="' + dataRangeId + '"]').bind('apply.daterangepicker', function () {
+ //获取时间范围,查询
+ // 都设置为0点
+ setTime($(this));
+ // 更新tooltip内容
+ $(this).attr("data-original-title", $(this).val());
+ });
+
+ $('input[id="' + dataRangeId + '"]').daterangepicker(optionSet1);
+
+};
+
+//关闭打开datarangepicker选择器
+alarmsUtil.dateRangeEnableDisable = function (customDateRangeId) {
+
+ $('#' + customDateRangeId).on('ifChecked', function () {
+
+ if (customDateRangeId == "customAckTime") {
+ vm.dataRangeLocationDisabled = false;
+ if(vm.fmConds.ackTimeStarTime!=null && vm.fmConds.ackTimeEndTime!=null){
+ vm.fmConds.ackTimeMode=0;
+ }
+ } else if (customDateRangeId == "customRaisedTime") {
+ vm.dataRangeTypeDisabled = false;
+ if(vm.fmConds.alarmRaisedStartTime!=null && vm.fmConds.alarmRaisedEndTime!=null){
+ vm.fmConds.alarmRaisedTimeMode=0;
+ }
+ } else if (customDateRangeId == "customClearTime"){
+ vm.dataRangeCodeDisabled = false;
+ if(vm.fmConds.clearedTimeStartTime!=null && vm.fmConds.clearedTimeEndTime!=null){
+ vm.fmConds.clearedTimeMode=0;
+ }
+ }
+ });
+ //setTime($('#' + dataRangeId));
+
+ $('#' + customDateRangeId).on('ifUnchecked', function () {
+
+ if (customDateRangeId == "customAckTime") {
+
+ vm.dataRangeLocationDisabled = true;
+ vm.fmConds.ackTimeMode=null;
+
+ } else if (customDateRangeId == "customRaisedTime") {
+
+ vm.dataRangeTypeDisabled = true;
+ vm.fmConds.alarmRaisedTimeMode=null;
+
+ } else if (customDateRangeId == "customClearTime"){
+
+ vm.dataRangeCodeDisabled = true;
+ vm.fmConds.clearedTimeMode=null;
+
+ }
+ });
+
+}
+
+//checkbox时间选择
+alarmsUtil.dateRangeCustom = function (vm) {
+
+ $("input[name=timeConfirm]").on("ifClicked", function () {
+ if ($(this).parent().hasClass("checked")) {
+ $(this).iCheck('uncheck');
+ }
+ });
+
+ $("input[name=timeOccur]").on("ifClicked", function () {
+ if ($(this).parent().hasClass("checked")) {
+ $(this).iCheck('uncheck');
+ }
+ });
+
+ $("input[name=timeClear]").on("ifClicked", function () {
+ if ($(this).parent().hasClass("checked")) {
+ $(this).iCheck('uncheck');
+ }
+ });
+
+ $("input[cond_id=time]").on('ifChecked', function () {
+
+ var nowTime = (new Date()).toLocaleDateString();
+ var condDate = $(this).attr("cond_value");
+
+ if ($(this).attr("name") == "timeConfirm") {
+ if (condDate == "1") {
+ vm.fmConds.ackRelativeTime = 1 * 24 * 60 * 60 * 1000;
+ vm.fmConds.ackTimeMode = 1;
+ } else if (condDate == "2") {
+ vm.fmConds.ackRelativeTime = 2 * 24 * 60 * 60 * 1000;
+ vm.fmConds.ackTimeMode = 1;
+ } else if (condDate == "7") {
+ vm.fmConds.ackRelativeTime = 7 * 24 * 60 * 60 * 1000;
+ vm.fmConds.ackTimeMode = 1;
+ }
+ }
+
+ if ($(this).attr("name") == "timeOccur") {
+ if (condDate == "1") {
+ vm.fmConds.alarmRaisedRelativeTime = 1 * 24 * 60 * 60 * 1000;
+ vm.fmConds.alarmRaisedTimeMode = 1;
+ } else if (condDate == "2") {
+ vm.fmConds.alarmRaisedRelativeTime = 2 * 24 * 60 * 60 * 1000;
+ vm.fmConds.alarmRaisedTimeMode = 1;
+ } else if (condDate == "7") {
+ vm.fmConds.alarmRaisedRelativeTime = 7 * 24 * 60 * 60 * 1000;
+ vm.fmConds.alarmRaisedTimeMode = 1;
+ }
+ }
+
+ if ($(this).attr("name") == "timeClear") {
+ if (condDate == "1") {
+ vm.fmConds.clearedTimeRelativeTime =1 * 24 * 60 * 60 * 1000;
+ vm.fmConds.clearedTimeMode = 1;
+ } else if (condDate == "2") {
+ vm.fmConds.clearedTimeRelativeTime =2 * 24 * 60 * 60 * 1000;
+ vm.fmConds.clearedTimeMode = 1;
+ } else if (condDate == "7") {
+ vm.fmConds.clearedTimeRelativeTime =7 * 24 * 60 * 60 * 1000;
+ vm.fmConds.clearedTimeMode = 1;
+ }
+ }
+
+ //refreshByCond();
+ });
+
+ $("input[cond_id=time]").on('ifUnchecked', function () {
+ if ($(this).attr("name") == "timeConfirm") {
+ vm.fmConds.ackRelativeTime = null;
+ vm.fmConds.ackTimeMode = null;
+ }else if ($(this).attr("name") == "timeOccur") {
+ vm.fmConds.alarmRaisedRelativeTime = null;
+ vm.fmConds.alarmRaisedTimeMode = null;
+ }else if ($(this).attr("name") == "timeClear") {
+ vm.fmConds.clearedTimeRelativeTime = null;
+ vm.fmConds.clearedTimeMode = null;
+ }
+ });
+
+}
+
+
+/*格式化日期*/
+Date.prototype.format = function (format) {
+
+ /*
+
+ * format="yyyy-MM-dd hh:mm:ss";
+
+ */
+ var o = {
+ "M+" : this.getMonth() + 1,
+ "d+" : this.getDate(),
+ "h+" : this.getHours(),
+ "m+" : this.getMinutes(),
+ "s+" : this.getSeconds(),
+ "q+" : Math.floor((this.getMonth() + 3) / 3),
+ "S" : this.getMilliseconds()
+ }
+ if (/(y+)/.test(format)) {
+ format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
+ - RegExp.$1.length));
+ }
+ for (var k in o) {
+ if (new RegExp("(" + k + ")").test(format)) {
+ format = format.replace(RegExp.$1, RegExp.$1.length == 1
+ ? o[k]
+ : ("00" + o[k]).substr(("" + o[k]).length));
+ }
+ }
+ return format;
+
+}
+
+//daterangepicker设置时间
+function setTime($obj) {
+
+ var title = $obj.attr('dtitle');
+ var arr = $obj.val().split(' - ');
+ //排除日历组件空字符串的情况。
+ if (arr[0] != '') {
+ var starTime = new Date(arr[0].replace(/-/g, "/")).getTime();
+ var endTime = new Date(arr[1].replace(/-/g, "/")).getTime();
+ if (title == "ackTime") {
+ vm.fmConds.ackTimeStarTime = starTime;
+ vm.fmConds.ackTimeEndTime = endTime;
+ vm.fmConds.ackTimeMode=0;
+ } else if (title == "raisedTime") {
+ vm.fmConds.alarmRaisedStartTime = starTime;
+ vm.fmConds.alarmRaisedEndTime = endTime;
+ vm.fmConds.alarmRaisedTimeMode=0;
+ } else if (title == "clearTime") {
+ vm.fmConds.clearedTimeStartTime = starTime;
+ vm.fmConds.clearedTimeEndTime = endTime;
+ vm.fmConds.clearedTimeMode=0;
+ }
+ }
+}
+
+/*
+@param type 1 day 2 week 3 month 4 year
+ */
+function reduceDate(date, val, type) {
+
+ var d = new Date(date);
+ if (type == 'day') {
+ d.setDate(d.getDate() - val);
+ } else if (type == 'week') {
+ d.setDate(d.getDate() - val * 7);
+ } else if (type == 'month') {
+ d.setMonth(d.getMonth() - val);
+ } else if (type == 'year') {
+ d.setFullYear(d.getFullYear() - val);
+ }
+ var month = d.getMonth() + 1;
+ var day = d.getDate();
+ if (month < 10) {
+ month = "0" + month;
+ }
+ if (day < 10) {
+ day = "0" + day;
+ }
+ var val = d.getFullYear() + "-" + month + "-" + day;
+ return val;
+}
+
+alarmsUtil.condSave = function (cond, saveUrl, name) {
+
+ var conds = [];
+ if (cond.severity != null && cond.severity != "undefined" && cond.severity.length > 0) {
+ var severity = '{ "type": "Severity", "data": [{"severity": "' + cond.severity + '"}]}'; //级别
+ var severityObj = window.JSON.parse(severity)
+ conds.push(severityObj);
+ }
+ if (cond.ackState != null && cond.ackState != "undefined") {
+ var ackState = '{ "type": "AckState", "data": [{"ackState": "' + cond.ackState + '"}]}'; //级别
+ var ackStateObj = window.JSON.parse(ackState)
+ conds.push(ackStateObj);
+ }
+ if (cond.filterState != null && cond.filterState != "undefined") {
+ var filterState = '{ "type": "FilterState", "data": [{"filterState": "' + cond.filterState + '"}]}'; //级别
+ var filterStateObj = window.JSON.parse(filterState)
+ conds.push(filterStateObj);
+ }
+
+ if (cond.ackTimeStarTime != null && cond.ackTimeStarTime != "undefined") {
+ var ackTime = '{ "type": "AckTime", "data": [{"mode":"0","start":"' + cond.ackTimeStarTime + '","end":"' + cond.ackTimeEndTime + '" }]}'; //级别
+ var ackTimeObj = window.JSON.parse(ackTime)
+ conds.push(ackTimeObj);
+ }
+ if (cond.alarmRaisedStartTime != null && cond.alarmRaisedStartTime != "undefined") {
+ var alarmRaisedTime = '{ "type": "RaisedTime", "data": [{"mode":"0","start":"' + cond.alarmRaisedStartTime + '","end":"' + cond.alarmRaisedEndTime + '" }]}'; //级别
+ var alarmRaisedTimeObj = window.JSON.parse(alarmRaisedTime)
+ conds.push(alarmRaisedTimeObj);
+ }
+
+ if (cond.clearedTimeStarTime != null && cond.clearedTimeStarTime != "undefined") {
+ var clearedTime = '{ "type": "ClearedTime", "data": [{"mode":"0","start":"' + cond.clearedTimeStarTime + '","end":"' + cond.clearedTimeEndime + '" }]}'; //级别
+ var severityObj = window.JSON.parse(clearedTime)
+ conds.push(severityObj);
+ }
+ var resJsonObj = AlarmConds.parseActiveConds2JSon(conds);
+ resJsonObj.rule.name = name;
+ resJsonObj.rule.ruleType = vm.ruleType;
+ var resStr = window.JSON.stringify(resJsonObj);
+ var dataSource = "isc_AosRestDataSource_1";
+ var operationType = "add";
+ var data1 = {
+ dataSource : dataSource,
+ operationType : operationType,
+ data : resJsonObj,
+ oldValues : null
+ };
+ $.ajax({
+ dataType : "json",
+ type : "POST",
+ contentType : 'application/json; charset=utf-8',
+ url : saveUrl,
+ data : JSON.stringify(data1),
+ async : false,
+ success : function (msg) {
+ $('#saveModalCancle').trigger("click");
+ }
+ });
+
+}
+
+Array.prototype.contains = function (item) {
+ return RegExp("(^|,)" + item.toString() + "($|,)").test(this);
+};
+
+/*
+@param alarmsType 1当前告警 2历史告警
+@param condRuleId 查询条件的RuleId
+ */
+alarmsUtil.queryByParma = function (alarmsType, condRuleId) {
+
+ //1.判断是当前告警还是历史告警。
+
+ var sourceUrl;
+ if (alarmsType == 1) { //当前告警
+ sourceUrl = '/web/rest/web/fm/curqueryview?' + 'data={"ruleType":1,"ruleSort":1}&isc_flag=smartClient&_operationType=fetch&_startRow=0&_endRow=75&_textMatchStyle=exact&_componentId=condList&_dataSource=isc_RestDataSource_7&isc_metaDataPrefix=_&isc_dataFormat=json';
+ vm.ruleType = 1;
+ vm.$queryAlarmsInfoUrl = "/ngict/rest/fm/curalarms";
+ vm.curalarmsType = "curalarms";
+ vm.showClear = true; //清除按钮
+
+ } else if(alarmsType == 2){ //历史告警
+
+ sourceUrl = '/web/rest/web/fm/curqueryview?' + 'data={"ruleType":2,"ruleSort":1}&isc_flag=smartClient&_operationType=fetch&_startRow=0&_endRow=75&_textMatchStyle=exact&_componentId=condList&_dataSource=isc_RestDataSource_7&isc_metaDataPrefix=_&isc_dataFormat=json';
+ vm.ruleType = 2;
+ vm.$queryAlarmsInfoUrl = "/ngict/rest/fm/hisalarms";
+ vm.hisalarmsType = "hisalarms";
+ vm.showClear = false; //清除按钮
+ }else if(alarmsType == 3){ //通知
+ sourceUrl = '/web/rest/web/fm/curqueryview?' + 'data={"ruleType":2,"ruleSort":1}&isc_flag=smartClient&_operationType=fetch&_startRow=0&_endRow=75&_textMatchStyle=exact&_componentId=condList&_dataSource=isc_RestDataSource_7&isc_metaDataPrefix=_&isc_dataFormat=json';
+ vm.ruleType = 3;
+ vm.$queryAlarmsInfoUrl = "/ngict/rest/fm/notify";
+ vm.notificationType = "notification";
+ vm.showClear = false; //清除按钮
+ }
+
+ //如果没传condRuleId 直接返回
+ if (condRuleId == null || condRuleId == "undefined") {
+ return;
+ }
+
+ //2.取出告警规则的数据。
+
+ $.ajax({
+ type : "get",
+ data : null,
+ url : sourceUrl,
+ async : false,
+ success : function (msg) {
+ //1.遍历返回的条件数组确定是哪一个rule规则。
+ var ruleCondArr = msg.response.data;
+ var xmlData = "";
+ for (var i = 0; i < ruleCondArr.length; i++) {
+ if (ruleCondArr[i].ruleId == condRuleId) { //condRuleId
+ xmlData = "<xml>" + ruleCondArr[i].ruleData + "</xml>" //在jQuery裡,如果要直接将字串转成XML物件,记得前后方要加上<xml>及</xml>,才会被当成XML处理;
+ break;
+ }
+ };
+
+ //3.解析数据的xml联动页面的组件。
+ $(xmlData).find("CompoundCond").each(function () {
+ //1.级别
+ for (var i = 0; i < vm.severityTypes.length; i++) {
+ vm.severityTypes[i].value = false;
+ }
+ if ($(this).find("PerceivedSeverity").attr('value') != null && $(this).find("PerceivedSeverity ").attr('value') != 'undefined') {
+ var perceivedSeverityArr = $(this).find("PerceivedSeverity ").attr('value').split(',');
+ for (var i = 0; i < perceivedSeverityArr.length; i++) {
+ if (perceivedSeverityArr.contains(vm.severityTypes[i].id)) {
+ vm.severityTypes[i].value = true;
+ }
+ };
+ }
+
+ //2.确认状态
+ for (var i = 0; i < vm.ackStateTypes.length; i++) {
+ vm.ackStateTypes[i].value = false;
+ };
+ var ackStateV = $(this).find("AckState").attr('value');
+ if (ackStateV != null && ackStateV != "undefined") {
+ var ackStateArr = ackStateV.split(',');
+ for (var i = 0; i < vm.ackStateTypes.length; i++) {
+ if (ackStateArr.contains(vm.ackStateTypes[i].id)) {
+ vm.ackStateTypes[i].value = true;
+ }
+ };
+ }
+
+ //3.可见性
+ if(vm.ruleType === 1){
+ for (var i = 0; i < vm.filterStateTypes.length; i++) {
+ vm.filterStateTypes[i].value = false;
+ };
+ var filterStateV = $(this).find("FilterState").attr('value')
+ if (filterStateV != null && filterStateV != "undefined") {
+ var filterStateArr = filterStateV.split(',');
+ for (var i = 0; i < vm.filterStateTypes.length; i++) {
+ if (filterStateArr.contains(vm.filterStateTypes[i].id)) {
+ vm.filterStateTypes[i].value = true;
+ }
+ };
+ }
+ }
+ //4.确认时间
+
+ var dataRangeAck = $('input[dtitle="ackTime"]'); //日历组件
+ vm.fmConds.ackTimeStarTime = null;
+ vm.fmConds.ackTimeEndTime = null;
+ dataRangeAck.val('');
+ var ackTimeStartMs = $(this).find("AckTime").attr('start');
+ var ackTimeEndMs = $(this).find("AckTime").attr('end');
+ if (ackTimeStartMs != null && ackTimeStartMs != "undefined" && ackTimeEndMs != null && ackTimeEndMs != "undefined") {
+ vm.fmConds.ackTimeStarTime = ackTimeStartMs; //确认时间
+ vm.fmConds.ackTimeEndTime = ackTimeEndMs;
+ var ackTimeStarTime = new Date(parseInt(ackTimeStartMs)).format('yyyy-MM-dd');
+ var ackTimeEndTime = new Date(parseInt(ackTimeEndMs)).format('yyyy-MM-dd');
+ dataRangeAck.val(ackTimeStarTime + ' - ' + ackTimeEndTime);
+ }
+
+ //5.发生时间
+ vm.fmConds.alarmRaisedStartTime = null;
+ vm.fmConds.alarmRaisedEndTime = null;
+ var dataRangeRaised = $('input[dtitle="raisedTime"]'); //日历组件
+ dataRangeRaised.val('');
+ var raisedTimeStartMs = $(this).find("RaisedTime").attr('start');
+ var raisedTimeEndMs = $(this).find("RaisedTime").attr('end');
+ if (raisedTimeStartMs != null && raisedTimeStartMs != "undefined" && raisedTimeEndMs != null && raisedTimeEndMs != "undefined") {
+ vm.fmConds.alarmRaisedStartTime = raisedTimeStartMs; //发生时间
+ vm.fmConds.alarmRaisedEndTime = raisedTimeEndMs;
+ var raisedTimeStart = new Date(parseInt(raisedTimeStartMs)).format('yyyy-MM-dd');
+ var raisedTimeEnd = new Date(parseInt(raisedTimeEndMs)).format('yyyy-MM-dd');
+ dataRangeRaised.val(raisedTimeStart + ' - ' + raisedTimeEnd);
+ }
+
+ //6.清除时间
+
+
+ //7.告警码
+
+ vm.fmConds.probableCause = null;
+ var probableCauseArr = $(this).find("ProbableCause").attr('value');
+ if (probableCauseArr != null && probableCauseArr != "undefined") {
+ for (var i = 0; i < probableCauseArr.length; i++) {
+ vm.fmConds.probableCause = probableCauseArr;
+ // 联动
+ };
+ }
+
+ //8.告警位置
+ vm.fmConds.probableCause = null;
+ var newPositionCondArr = $(this).find("NewPositionCond").attr('value');
+ if (newPositionCondArr != null && newPositionCondArr != "undefined")
+ for (var i = 0; i < newPositionCondArr.length; i++) {
+ // 联动
+ };
+
+ //9.告警类型
+ vm.fmConds.alarmType = null;
+ var alarmTypeArr = $(this).find("AlarmType").attr('value');
+ if (alarmTypeArr != null && alarmTypeArr != "undefined") {
+ for (var i = 0; i < alarmTypeArr.length; i++) {
+ vm.fmConds.alarmType = alarmTypeArr;
+ };
+ }
+ });
+ }
+ });
+}
+
+
+/*
+ 获取系统类型中的告警码数量
+*/
+alarmsUtil.getProbableCauseCountBySystemType=function(systemType){
+
+ //"/ngict/rest/fm/probableCause?request={"systemTypes":[6,12]}"
+ var getData={};
+ var request={};
+ request.systemTypes=systemType;
+ getData.request = JSON.stringify(request);
+ $.ajax({
+ type : "get",
+ data : getData,
+ url : "/ngict/rest/fm/probableCause",
+ async : true,
+ success : function (msg) {
+ vm.alarmCodeSelectedCount+=msg.length;
+ }});
+}
\ No newline at end of file diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/avalon.modern.js b/umc-iui/src/main/resources/webroot/umc-fm/js/avalon.modern.js new file mode 100644 index 00000000..7c37393f --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/avalon.modern.js @@ -0,0 +1,4935 @@ +/*==================================================
+ Copyright (c) 2013-2015 司徒正美 and other contributors
+ http://www.cnblogs.com/rubylouvre/
+ https://github.com/RubyLouvre
+ http://weibo.com/jslouvre/
+
+ Released under the MIT license
+ avalon.modern.js 1.43 built in 2015.5.21
+ support IE10+ and other browsers
+ ==================================================*/
+(function (global, factory) {
+
+ if (typeof module === "object" && typeof module.exports === "object") {
+ // For CommonJS and CommonJS-like environments where a proper `window`
+ // is present, execute the factory and get avalon.
+ // For environments that do not have a `window` with a `document`
+ // (such as Node.js), expose a factory as module.exports.
+ // This accentuates the need for the creation of a real `window`.
+ // e.g. var avalon = require("avalon")(window);
+ module.exports = global.document ? factory(global, true) : function (w) {
+ if (!w.document) {
+ throw new Error("Avalon requires a window with a document")
+ }
+ return factory(w)
+ }
+ } else {
+ factory(global)
+ }
+
+// Pass this if window is not defined yet
+}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
+
+ /*********************************************************************
+ * 全局变量及方法 *
+ **********************************************************************/
+ var expose = Date.now()
+//http://stackoverflow.com/questions/7290086/javascript-use-strict-and-nicks-find-global-function
+ var DOC = window.document
+ var head = DOC.head //HEAD元素
+ head.insertAdjacentHTML("afterBegin", '<avalon ms-skip class="avalonHide"><style id="avalonStyle">.avalonHide{ display: none!important }</style></avalon>')
+ var ifGroup = head.firstChild
+
+ function log() {
+ if (avalon.config.debug) {
+// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
+ console.log.apply(console, arguments)
+ }
+ }
+
+ /**
+ * Creates a new object without a prototype. This object is useful for lookup without having to
+ * guard against prototypically inherited properties via hasOwnProperty.
+ *
+ * Related micro-benchmarks:
+ * - http://jsperf.com/object-create2
+ * - http://jsperf.com/proto-map-lookup/2
+ * - http://jsperf.com/for-in-vs-object-keys2
+ */
+ function createMap() {
+ return Object.create(null)
+ }
+
+ var subscribers = "$" + expose
+ var otherRequire = window.require
+ var otherDefine = window.define
+ var innerRequire
+ var stopRepeatAssign = false
+ var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
+ var rcomplexType = /^(?:object|array)$/
+ var rsvg = /^\[object SVG\w*Element\]$/
+ var rwindow = /^\[object (?:Window|DOMWindow|global)\]$/
+ var oproto = Object.prototype
+ var ohasOwn = oproto.hasOwnProperty
+ var serialize = oproto.toString
+ var ap = Array.prototype
+ var aslice = ap.slice
+ var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
+ var W3C = window.dispatchEvent
+ var root = DOC.documentElement
+ var hyperspace = DOC.createDocumentFragment()
+ var cinerator = DOC.createElement("div")
+ var class2type = {}
+ "Boolean Number String Function Array Date RegExp Object Error".replace(rword, function (name) {
+ class2type["[object " + name + "]"] = name.toLowerCase()
+ })
+
+
+ function noop() {
+ }
+
+
+ function oneObject(array, val) {
+ if (typeof array === "string") {
+ array = array.match(rword) || []
+ }
+ var result = {},
+ value = val !== void 0 ? val : 1
+ for (var i = 0, n = array.length; i < n; i++) {
+ result[array[i]] = value
+ }
+ return result
+ }
+
+//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
+ var generateID = function (prefix) {
+ prefix = prefix || "avalon"
+ return String(Math.random() + Math.random()).replace(/\d\.\d{4}/, prefix)
+ }
+
+ function IE() {
+ if (window.VBArray) {
+ var mode = document.documentMode
+ return mode ? mode : window.XMLHttpRequest ? 7 : 6
+ } else {
+ return 0
+ }
+ }
+
+ var IEVersion = IE()
+
+ avalon = function (el) { //创建jQuery式的无new 实例化结构
+ return new avalon.init(el)
+ }
+
+ /*视浏览器情况采用最快的异步回调*/
+ avalon.nextTick = new function () {// jshint ignore:line
+ var tickImmediate = window.setImmediate
+ var tickObserver = window.MutationObserver
+ var tickPost = W3C && window.postMessage
+ if (tickImmediate) {
+ return tickImmediate.bind(window)
+ }
+
+ var queue = []
+
+ function callback() {
+ var n = queue.length
+ for (var i = 0; i < n; i++) {
+ queue[i]()
+ }
+ queue = queue.slice(n)
+ }
+
+ if (tickObserver) {
+ var node = document.createTextNode("avalon")
+ new tickObserver(callback).observe(node, {characterData: true})// jshint ignore:line
+ return function (fn) {
+ queue.push(fn)
+ node.data = Math.random()
+ }
+ }
+
+ if (tickPost) {
+ window.addEventListener("message", function (e) {
+ var source = e.source
+ if ((source === window || source === null) && e.data === "process-tick") {
+ e.stopPropagation()
+ callback()
+ }
+ })
+
+ return function (fn) {
+ queue.push(fn)
+ window.postMessage('process-tick', '*')
+ }
+ }
+
+ return function (fn) {
+ setTimeout(fn, 0)
+ }
+ }// jshint ignore:line
+ /*********************************************************************
+ * avalon的静态方法定义区 *
+ **********************************************************************/
+ avalon.init = function (el) {
+ this[0] = this.element = el
+ }
+ avalon.fn = avalon.prototype = avalon.init.prototype
+
+ avalon.type = function (obj) { //取得目标的类型
+ if (obj == null) {
+ return String(obj)
+ }
+ // 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[serialize.call(obj)] || "object" :
+ typeof obj
+ }
+
+ var isFunction = function (fn) {
+ return serialize.call(fn) === "[object Function]"
+ }
+
+ avalon.isFunction = isFunction
+
+ avalon.isWindow = function (obj) {
+ return rwindow.test(serialize.call(obj))
+ }
+
+ /*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
+
+ avalon.isPlainObject = function (obj) {
+ // 简单的 typeof obj === "object"检测,会致使用isPlainObject(window)在opera下通不过
+ return serialize.call(obj) === "[object Object]" && Object.getPrototypeOf(obj) === oproto
+ }
+
+//与jQuery.extend方法,可用于浅拷贝,深拷贝
+ avalon.mix = avalon.fn.mix = function () {
+ var options, name, src, copy, copyIsArray, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false
+
+ // 如果第一个参数为布尔,判定是否深拷贝
+ if (typeof target === "boolean") {
+ deep = target
+ target = arguments[1] || {}
+ i++
+ }
+
+ //确保接受方为一个复杂的数据类型
+ if (typeof target !== "object" && !isFunction(target)) {
+ target = {}
+ }
+
+ //如果只有一个参数,那么新成员添加于mix所在的对象上
+ if (i === length) {
+ target = this
+ i--
+ }
+
+ for (; i < length; i++) {
+ //只处理非空参数
+ if ((options = arguments[i]) != null) {
+ for (name in options) {
+ src = target[name]
+ copy = options[name]
+ // 防止环引用
+ if (target === copy) {
+ continue
+ }
+ if (deep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
+
+ if (copyIsArray) {
+ copyIsArray = false
+ clone = src && Array.isArray(src) ? src : []
+
+ } else {
+ clone = src && avalon.isPlainObject(src) ? src : {}
+ }
+
+ target[name] = avalon.mix(deep, clone, copy)
+ } else if (copy !== void 0) {
+ target[name] = copy
+ }
+ }
+ }
+ }
+ return target
+ }
+
+ function _number(a, len) { //用于模拟slice, splice的效果
+ a = Math.floor(a) || 0
+ return a < 0 ? Math.max(len + a, 0) : Math.min(a, len);
+ }
+
+ avalon.mix({
+ rword: rword,
+ subscribers: subscribers,
+ version: 1.43,
+ ui: {},
+ log: log,
+ slice: function (nodes, start, end) {
+ return aslice.call(nodes, start, end)
+ },
+ noop: noop,
+ /*如果不用Error对象封装一下,str在控制台下可能会乱码*/
+ error: function (str, e) {
+ throw new (e || Error)(str)// jshint ignore:line
+ },
+ /*将一个以空格或逗号隔开的字符串或数组,转换成一个键值都为1的对象*/
+ oneObject: oneObject,
+ /* avalon.range(10)
+ => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+ avalon.range(1, 11)
+ => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ avalon.range(0, 30, 5)
+ => [0, 5, 10, 15, 20, 25]
+ avalon.range(0, -10, -1)
+ => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
+ avalon.range(0)
+ => []*/
+ range: function (start, end, step) { // 用于生成整数数组
+ step || (step = 1)
+ if (end == null) {
+ end = start || 0
+ start = 0
+ }
+ var index = -1,
+ length = Math.max(0, Math.ceil((end - start) / step)),
+ result = new Array(length)
+ while (++index < length) {
+ result[index] = start
+ start += step
+ }
+ return result
+ },
+ eventHooks: {},
+ /*绑定事件*/
+ bind: function (el, type, fn, phase) {
+ var hooks = avalon.eventHooks
+ var hook = hooks[type]
+ if (typeof hook === "object") {
+ type = hook.type
+ if (hook.deel) {
+ fn = hook.deel(el, type, fn, phase)
+ }
+ }
+ if (!fn.unbind)
+ el.addEventListener(type, fn, !!phase)
+ return fn
+ },
+ /*卸载事件*/
+ unbind: function (el, type, fn, phase) {
+ var hooks = avalon.eventHooks
+ var hook = hooks[type]
+ var callback = fn || noop
+ if (typeof hook === "object") {
+ type = hook.type
+ if (hook.deel) {
+ fn = hook.deel(el, type, fn, false)
+ }
+ }
+ el.removeEventListener(type, callback, !!phase)
+ },
+ /*读写删除元素节点的样式*/
+ css: function (node, name, value) {
+ if (node instanceof avalon) {
+ node = node[0]
+ }
+ var prop = /[_-]/.test(name) ? camelize(name) : name, fn
+ name = avalon.cssName(prop) || prop
+ if (value === void 0 || typeof value === "boolean") { //获取样式
+ fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
+ if (name === "background") {
+ name = "backgroundColor"
+ }
+ var val = fn(node, name)
+ return value === true ? parseFloat(val) || 0 : val
+ } else if (value === "") { //请除样式
+ node.style[name] = ""
+ } else { //设置样式
+ if (value == null || value !== value) {
+ return
+ }
+ if (isFinite(value) && !avalon.cssNumber[prop]) {
+ value += "px"
+ }
+ fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
+ fn(node, name, value)
+ }
+ },
+ /*遍历数组与对象,回调的第一个参数为索引或键名,第二个或元素或键值*/
+ each: function (obj, fn) {
+ if (obj) { //排除null, undefined
+ var i = 0
+ if (isArrayLike(obj)) {
+ for (var n = obj.length; i < n; i++) {
+ if (fn(i, obj[i]) === false)
+ break
+ }
+ } else {
+ for (i in obj) {
+ if (obj.hasOwnProperty(i) && fn(i, obj[i]) === false) {
+ break
+ }
+ }
+ }
+ }
+ },
+ //收集元素的data-{{prefix}}-*属性,并转换为对象
+ getWidgetData: function (elem, prefix) {
+ var raw = avalon(elem).data()
+ var result = {}
+ for (var i in raw) {
+ if (i.indexOf(prefix) === 0) {
+ result[i.replace(prefix, "").replace(/\w/, function (a) {
+ return a.toLowerCase()
+ })] = raw[i]
+ }
+ }
+ return result
+ },
+ Array: {
+ /*只有当前数组不存在此元素时只添加它*/
+ ensure: function (target, item) {
+ if (target.indexOf(item) === -1) {
+ return target.push(item)
+ }
+ },
+ /*移除数组中指定位置的元素,返回布尔表示成功与否*/
+ removeAt: function (target, index) {
+ return !!target.splice(index, 1).length
+ },
+ /*移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否*/
+ remove: function (target, item) {
+ var index = target.indexOf(item)
+ if (~index)
+ return avalon.Array.removeAt(target, index)
+ return false
+ }
+ }
+ })
+
+ var bindingHandlers = avalon.bindingHandlers = {}
+ var bindingExecutors = avalon.bindingExecutors = {}
+
+ /*判定是否类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
+ function isArrayLike(obj) {
+ if (obj && typeof obj === "object") {
+ var n = obj.length,
+ str = serialize.call(obj)
+ if (/(Array|List|Collection|Map|Arguments)\]$/.test(str)) {
+ return true
+ } else if (str === "[object Object]" && n === (n >>> 0)) {
+ return true //由于ecma262v5能修改对象属性的enumerable,因此不能用propertyIsEnumerable来判定了
+ }
+ }
+ return false
+ }
+
+
+// https://github.com/rsms/js-lru
+ var Cache = new function () {// jshint ignore:line
+ function LRU(maxLength) {
+ this.size = 0
+ this.limit = maxLength
+ this.head = this.tail = void 0
+ this._keymap = {}
+ }
+
+ var p = LRU.prototype
+
+ p.put = function (key, value) {
+ var entry = {
+ key: key,
+ value: value
+ }
+ this._keymap[key] = entry
+ if (this.tail) {
+ this.tail.newer = entry
+ entry.older = this.tail
+ } else {
+ this.head = entry
+ }
+ this.tail = entry
+ if (this.size === this.limit) {
+ this.shift()
+ } else {
+ this.size++
+ }
+ return value
+ }
+
+ p.shift = function () {
+ var entry = this.head
+ if (entry) {
+ this.head = this.head.newer
+ this.head.older =
+ entry.newer =
+ entry.older =
+ this._keymap[entry.key] = void 0
+ }
+ }
+ p.get = function (key) {
+ var entry = this._keymap[key]
+ if (entry === void 0)
+ return
+ if (entry === this.tail) {
+ return entry.value
+ }
+ // HEAD--------------TAIL
+ // <.older .newer>
+ // <--- add direction --
+ // A B C <D> E
+ if (entry.newer) {
+ if (entry === this.head) {
+ this.head = entry.newer
+ }
+ entry.newer.older = entry.older // C <-- E.
+ }
+ if (entry.older) {
+ entry.older.newer = entry.newer // C. --> E
+ }
+ entry.newer = void 0 // D --x
+ entry.older = this.tail // D. --> E
+ if (this.tail) {
+ this.tail.newer = entry // E. <-- D
+ }
+ this.tail = entry
+ return entry.value
+ }
+ return LRU
+ }// jshint ignore:line
+
+ /*********************************************************************
+ * DOM 底层补丁 *
+ **********************************************************************/
+//safari5+是把contains方法放在Element.prototype上而不是Node.prototype
+ if (!DOC.contains) {
+ Node.prototype.contains = function (arg) {
+ return !!(this.compareDocumentPosition(arg) & 16)
+ }
+ }
+ avalon.contains = function (root, el) {
+ try {
+ while ((el = el.parentNode))
+ if (el === root)
+ return true
+ return false
+ } catch (e) {
+ return false
+ }
+ }
+
+ if (window.SVGElement) {
+ var svgns = "http://www.w3.org/2000/svg"
+ var svg = DOC.createElementNS(svgns, "svg")
+ svg.innerHTML = '<circle cx="50" cy="50" r="40" fill="red" />'
+ if (!rsvg.test(svg.firstChild)) {// #409
+ /* jshint ignore:start */
+ function enumerateNode(node, targetNode) {
+ if (node && node.childNodes) {
+ var nodes = node.childNodes
+ for (var i = 0, el; el = nodes[i++];) {
+ if (el.tagName) {
+ var svg = DOC.createElementNS(svgns,
+ el.tagName.toLowerCase())
+ // copy attrs
+ ap.forEach.call(el.attributes, function (attr) {
+ svg.setAttribute(attr.name, attr.value)
+ })
+ // 递归处理子节点
+ enumerateNode(el, svg)
+ targetNode.appendChild(svg)
+ }
+ }
+ }
+ }
+
+ /* jshint ignore:end */
+ Object.defineProperties(SVGElement.prototype, {
+ "outerHTML": {//IE9-11,firefox不支持SVG元素的innerHTML,outerHTML属性
+ enumerable: true,
+ configurable: true,
+ get: function () {
+ return new XMLSerializer().serializeToString(this)
+ },
+ set: function (html) {
+ var tagName = this.tagName.toLowerCase(),
+ par = this.parentNode,
+ frag = avalon.parseHTML(html)
+ // 操作的svg,直接插入
+ if (tagName === "svg") {
+ par.insertBefore(frag, this)
+ // svg节点的子节点类似
+ } else {
+ var newFrag = DOC.createDocumentFragment()
+ enumerateNode(frag, newFrag)
+ par.insertBefore(newFrag, this)
+ }
+ par.removeChild(this)
+ }
+ },
+ "innerHTML": {
+ enumerable: true,
+ configurable: true,
+ get: function () {
+ var s = this.outerHTML
+ var ropen = new RegExp("<" + this.nodeName + '\\b(?:(["\'])[^"]*?(\\1)|[^>])*>', "i")
+ var rclose = new RegExp("<\/" + this.nodeName + ">$", "i")
+ return s.replace(ropen, "").replace(rclose, "")
+ },
+ set: function (html) {
+ if (avalon.clearHTML) {
+ avalon.clearHTML(this)
+ var frag = avalon.parseHTML(html)
+ enumerateNode(frag, this)
+ }
+ }
+ }
+ })
+ }
+ }
+//========================= event binding ====================
+ var eventHooks = avalon.eventHooks
+//针对firefox, chrome修正mouseenter, mouseleave(chrome30+)
+ if (!("onmouseenter" in root)) {
+ avalon.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+ }, function (origType, fixType) {
+ eventHooks[origType] = {
+ type: fixType,
+ deel: function (elem, _, fn) {
+ return function (e) {
+ var t = e.relatedTarget
+ if (!t || (t !== elem && !(elem.compareDocumentPosition(t) & 16))) {
+ delete e.type
+ e.type = origType
+ return fn.call(elem, e)
+ }
+ }
+ }
+ }
+ })
+ }
+//针对IE9+, w3c修正animationend
+ avalon.each({
+ AnimationEvent: "animationend",
+ WebKitAnimationEvent: "webkitAnimationEnd"
+ }, function (construct, fixType) {
+ if (window[construct] && !eventHooks.animationend) {
+ eventHooks.animationend = {
+ type: fixType
+ }
+ }
+ })
+
+ if (DOC.onmousewheel === void 0) {
+ /* IE6-11 chrome mousewheel wheelDetla 下 -120 上 120
+ firefox DOMMouseScroll detail 下3 上-3
+ firefox wheel detlaY 下3 上-3
+ IE9-11 wheel deltaY 下40 上-40
+ chrome wheel deltaY 下100 上-100 */
+ eventHooks.mousewheel = {
+ type: "wheel",
+ deel: function (elem, _, fn) {
+ return function (e) {
+ e.wheelDeltaY = e.wheelDelta = e.deltaY > 0 ? -120 : 120
+ e.wheelDeltaX = 0
+ Object.defineProperty(e, "type", {
+ value: "mousewheel"
+ })
+ fn.call(elem, e)
+ }
+ }
+ }
+ }
+
+ /*********************************************************************
+ * 配置系统 *
+ **********************************************************************/
+
+ function kernel(settings) {
+ for (var p in settings) {
+ if (!ohasOwn.call(settings, p))
+ continue
+ var val = settings[p]
+ if (typeof kernel.plugins[p] === "function") {
+ kernel.plugins[p](val)
+ } else if (typeof kernel[p] === "object") {
+ avalon.mix(kernel[p], val)
+ } else {
+ kernel[p] = val
+ }
+ }
+ return this
+ }
+
+ var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
+
+ function escapeRegExp(target) {
+ //http://stevenlevithan.com/regex/xregexp/
+ //将字符串安全格式化为正则表达式的源码
+ return (target + "").replace(rregexp, "\\$&")
+ }
+
+ var plugins = {
+ loader: function (builtin) {
+ var flag = innerRequire && builtin
+ window.require = flag ? innerRequire : otherRequire
+ window.define = flag ? innerRequire.define : otherDefine
+ },
+ interpolate: function (array) {
+ openTag = array[0]
+ closeTag = array[1]
+ if (openTag === closeTag) {
+ throw new SyntaxError("openTag!==closeTag")
+ } else if (array + "" === "<!--,-->") {
+ kernel.commentInterpolate = true
+ } else {
+ var test = openTag + "test" + closeTag
+ cinerator.innerHTML = test
+ if (cinerator.innerHTML !== test && cinerator.innerHTML.indexOf("<") > -1) {
+ throw new SyntaxError("此定界符不合法")
+ }
+ cinerator.innerHTML = ""
+ }
+ var o = escapeRegExp(openTag),
+ c = escapeRegExp(closeTag)
+ rexpr = new RegExp(o + "(.*?)" + c)
+ rexprg = new RegExp(o + "(.*?)" + c, "g")
+ rbind = new RegExp(o + ".*?" + c + "|\\sms-")
+ }
+ }
+
+ kernel.debug = true
+ kernel.plugins = plugins
+ kernel.plugins['interpolate'](["{{", "}}"])
+ kernel.paths = {}
+ kernel.shim = {}
+ kernel.maxRepeatSize = 100
+ avalon.config = kernel
+ var ravalon = /(\w+)\[(avalonctrl)="(\S+)"\]/
+ var findNodes = function (str) {
+ return DOC.querySelectorAll(str)
+ }
+ /*********************************************************************
+ * 事件总线 *
+ **********************************************************************/
+ var EventBus = {
+ $watch: function (type, callback) {
+ if (typeof callback === "function") {
+ var callbacks = this.$events[type]
+ if (callbacks) {
+ callbacks.push(callback)
+ } else {
+ this.$events[type] = [callback]
+ }
+ } else { //重新开始监听此VM的第一重简单属性的变动
+ this.$events = this.$watch.backup
+ }
+ return this
+ },
+ $unwatch: function (type, callback) {
+ var n = arguments.length
+ if (n === 0) { //让此VM的所有$watch回调无效化
+ this.$watch.backup = this.$events
+ this.$events = {}
+ } else if (n === 1) {
+ this.$events[type] = []
+ } else {
+ var callbacks = this.$events[type] || []
+ var i = callbacks.length
+ while (~--i < 0) {
+ if (callbacks[i] === callback) {
+ return callbacks.splice(i, 1)
+ }
+ }
+ }
+ return this
+ },
+ $fire: function (type) {
+ var special, i, v, callback
+ if (/^(\w+)!(\S+)$/.test(type)) {
+ special = RegExp.$1
+ type = RegExp.$2
+ }
+ var events = this.$events
+ if (!events)
+ return
+ var args = aslice.call(arguments, 1)
+ var detail = [type].concat(args)
+ if (special === "all") {
+ for (i in avalon.vmodels) {
+ v = avalon.vmodels[i]
+ if (v !== this) {
+ v.$fire.apply(v, detail)
+ }
+ }
+ } else if (special === "up" || special === "down") {
+ var elements = events.expr ? findNodes(events.expr) : []
+ if (elements.length === 0)
+ return
+ for (i in avalon.vmodels) {
+ v = avalon.vmodels[i]
+ if (v !== this) {
+ if (v.$events.expr) {
+ var eventNodes = findNodes(v.$events.expr)
+ if (eventNodes.length === 0) {
+ continue
+ }
+ //循环两个vmodel中的节点,查找匹配(向上匹配或者向下匹配)的节点并设置标识
+ /* jshint ignore:start */
+ Array.prototype.forEach.call(eventNodes, function (node) {
+ Array.prototype.forEach.call(elements, function (element) {
+ var ok = special === "down" ? element.contains(node) : //向下捕获
+ node.contains(element) //向上冒泡
+ if (ok) {
+ node._avalon = v //符合条件的加一个标识
+ }
+ });
+ })
+ /* jshint ignore:end */
+ }
+ }
+ }
+ var nodes = DOC.getElementsByTagName("*") //实现节点排序
+ var alls = []
+ Array.prototype.forEach.call(nodes, function (el) {
+ if (el._avalon) {
+ alls.push(el._avalon)
+ el._avalon = ""
+ el.removeAttribute("_avalon")
+ }
+ })
+ if (special === "up") {
+ alls.reverse()
+ }
+ for (i = 0; callback = alls[i++];) {
+ if (callback.$fire.apply(callback, detail) === false) {
+ break
+ }
+ }
+ } else {
+ var callbacks = events[type] || []
+ var all = events.$all || []
+ for (i = 0; callback = callbacks[i++];) {
+ if (isFunction(callback))
+ callback.apply(this, args)
+ }
+ for (i = 0; callback = all[i++];) {
+ if (isFunction(callback))
+ callback.apply(this, arguments)
+ }
+ }
+ }
+ }
+
+ /*********************************************************************
+ * modelFactory *
+ **********************************************************************/
+//avalon最核心的方法的两个方法之一(另一个是avalon.scan),返回一个ViewModel(VM)
+ var VMODELS = avalon.vmodels = createMap() //所有vmodel都储存在这里
+ avalon.define = function (id, factory) {
+ var $id = id.$id || id
+ if (!$id) {
+ log("warning: vm必须指定$id")
+ }
+ if (VMODELS[$id]) {
+ log("warning: " + $id + " 已经存在于avalon.vmodels中")
+ }
+ if (typeof id === "object") {
+ var model = modelFactory(id)
+ } else {
+ var scope = {
+ $watch: noop
+ }
+ factory(scope) //得到所有定义
+ model = modelFactory(scope) //偷天换日,将scope换为model
+ stopRepeatAssign = true
+ factory(model)
+ stopRepeatAssign = false
+ }
+ model.$id = $id
+ return VMODELS[$id] = model
+ }
+
+//一些不需要被监听的属性
+ var $$skipArray = String("$id,$watch,$unwatch,$fire,$events,$model,$skipArray").match(rword)
+
+ function isObservable(name, value, $skipArray) {
+ if (isFunction(value) || value && value.nodeType) {
+ return false
+ }
+ if ($skipArray.indexOf(name) !== -1) {
+ return false
+ }
+ if ($$skipArray.indexOf(name) !== -1) {
+ return false
+ }
+ var $special = $skipArray.$special
+ if (name && name.charAt(0) === "$" && !$special[name]) {
+ return false
+ }
+ return true
+ }
+
+//ms-with,ms-each, ms-repeat绑定生成的代理对象储存池
+ var midway = createMap()
+
+ function getNewValue(accessor, name, value, $vmodel) {
+ switch (accessor.type) {
+ case 0://计算属性
+ var getter = accessor.get
+ var setter = accessor.set
+ if (isFunction(setter)) {
+ var $events = $vmodel.$events
+ var lock = $events[name]
+ $events[name] = [] //清空回调,防止内部冒泡而触发多次$fire
+ setter.call($vmodel, value)
+ $events[name] = lock
+ }
+ return getter.call($vmodel) //同步$model
+ case 1://监控属性
+ return value
+ case 2://对象属性(包括数组与哈希)
+ if (value !== $vmodel.$model[name]) {
+ var svmodel = accessor.svmodel = objectFactory($vmodel, name, value, accessor.valueType)
+ value = svmodel.$model //同步$model
+ var fn = midway[svmodel.$id]
+ fn && fn() //同步视图
+ }
+ return value
+ }
+ }
+
+ function modelFactory(source, $special, $model) {
+ if (Array.isArray(source)) {
+ var arr = source.concat()
+ source.length = 0
+ var collection = Collection(source)// jshint ignore:line
+ collection.pushArray(arr)
+ return collection
+ }
+ //0 null undefined || Node || VModel
+ if (!source || source.nodeType > 0 || (source.$id && source.$events)) {
+ return source
+ }
+ if (!Array.isArray(source.$skipArray)) {
+ source.$skipArray = []
+ }
+ source.$skipArray.$special = $special || createMap() //强制要监听的属性
+ var $vmodel = {} //要返回的对象, 它在IE6-8下可能被偷龙转凤
+ $model = $model || {} //vmodels.$model属性
+ var $events = createMap() //vmodel.$events属性
+ var watchedProperties = createMap() //监控属性
+ var initCallbacks = [] //初始化才执行的函数
+ for (var i in source) {
+ (function (name, val) {
+ $model[name] = val
+ if (!isObservable(name, val, source.$skipArray)) {
+ return //过滤所有非监控属性
+ }
+ //总共产生三种accessor
+ $events[name] = []
+ var valueType = avalon.type(val)
+ var accessor = function (newValue) {
+ var name = accessor._name
+ var $vmodel = this
+ var $model = $vmodel.$model
+ var oldValue = $model[name]
+ var $events = $vmodel.$events
+
+ if (arguments.length) {
+ if (stopRepeatAssign) {
+ return
+ }
+ //计算属性与对象属性需要重新计算newValue
+ if (accessor.type !== 1) {
+ newValue = getNewValue(accessor, name, newValue, $vmodel)
+ if (!accessor.type)
+ return
+ }
+ if (!isEqual(oldValue, newValue)) {
+ $model[name] = newValue
+ notifySubscribers($events[name]) //同步视图
+ safeFire($vmodel, name, newValue, oldValue) //触发$watch回调
+ }
+ } else {
+ if (accessor.type === 0) { //type 0 计算属性 1 监控属性 2 对象属性
+ //计算属性不需要收集视图刷新函数,都是由其他监控属性代劳
+ newValue = accessor.get.call($vmodel)
+ if (oldValue !== newValue) {
+ $model[name] = newValue
+ //这里不用同步视图
+ safeFire($vmodel, name, newValue, oldValue) //触发$watch回调
+ }
+ return newValue
+ } else {
+ collectSubscribers($events[name]) //收集视图函数
+ return accessor.svmodel || oldValue
+ }
+ }
+ }
+ //总共产生三种accessor
+ if (valueType === "object" && isFunction(val.get) && Object.keys(val).length <= 2) {
+ //第1种为计算属性, 因变量,通过其他监控属性触发其改变
+ accessor.set = val.set
+ accessor.get = val.get
+ accessor.type = 0
+ initCallbacks.push(function () {
+ var data = {
+ evaluator: function () {
+ data.type = Math.random(),
+ data.element = null
+ $model[name] = accessor.get.call($vmodel)
+ },
+ element: head,
+ type: Math.random(),
+ handler: noop,
+ args: []
+ }
+ Registry[expose] = data
+ accessor.call($vmodel)
+ delete Registry[expose]
+ })
+ } else if (rcomplexType.test(valueType)) {
+ //第2种为对象属性,产生子VM与监控数组
+ accessor.type = 2
+ accessor.valueType = valueType
+ initCallbacks.push(function () {
+ var svmodel = modelFactory(val, 0, $model[name])
+ accessor.svmodel = svmodel
+ svmodel.$events[subscribers] = $events[name]
+ })
+ } else {
+ accessor.type = 1
+ //第3种为监控属性,对应简单的数据类型,自变量
+ }
+ accessor._name = name
+ watchedProperties[name] = accessor
+ })(i, source[i])// jshint ignore:line
+ }
+
+ $$skipArray.forEach(function (name) {
+ delete source[name]
+ delete $model[name] //这些特殊属性不应该在$model中出现
+ })
+
+ $vmodel = Object.defineProperties($vmodel, descriptorFactory(watchedProperties), source) //生成一个空的ViewModel
+ for (var name in source) {
+ if (!watchedProperties[name]) {
+ $vmodel[name] = source[name]
+ }
+ }
+ //添加$id, $model, $events, $watch, $unwatch, $fire
+ $vmodel.$id = generateID()
+ $vmodel.$model = $model
+ $vmodel.$events = $events
+ for (i in EventBus) {
+ $vmodel[i] = EventBus[i]
+ }
+
+ Object.defineProperty($vmodel, "hasOwnProperty", {
+ value: function (name) {
+ return name in this.$model
+ },
+ writable: false,
+ enumerable: false,
+ configurable: true
+ })
+
+ initCallbacks.forEach(function (cb) { //收集依赖
+ cb()
+ })
+ return $vmodel
+ }
+
+//比较两个值是否相等
+ var isEqual = Object.is || function (v1, v2) {
+ if (v1 === 0 && v2 === 0) {
+ return 1 / v1 === 1 / v2
+ } else if (v1 !== v1) {
+ return v2 !== v2
+ } else {
+ return v1 === v2
+ }
+ }
+
+ function safeFire(a, b, c, d) {
+ if (a.$events) {
+ EventBus.$fire.call(a, b, c, d)
+ }
+ }
+
+ var descriptorFactory = function (obj) {
+ var descriptors = createMap()
+ for (var i in obj) {
+ descriptors[i] = {
+ get: obj[i],
+ set: obj[i],
+ enumerable: true,
+ configurable: true
+ }
+ }
+ return descriptors
+ }
+
+//应用于第2种accessor
+ function objectFactory(parent, name, value, valueType) {
+ //a为原来的VM, b为新数组或新对象
+ var son = parent[name]
+ if (valueType === "array") {
+ if (!Array.isArray(value) || son === value) {
+ return son //fix https://github.com/RubyLouvre/avalon/issues/261
+ }
+ son._.$unwatch()
+ son.clear()
+ son._.$watch()
+ son.pushArray(value.concat())
+ return son
+ } else {
+ var iterators = parent.$events[name]
+ var ret = modelFactory(value)
+ ret.$events[subscribers] = iterators
+ midway[ret.$id] = function (data) {
+ while (data = iterators.shift()) {
+ (function (el) {
+ avalon.nextTick(function () {
+ var type = el.type
+ if (type && bindingHandlers[type]) { //#753
+ el.rollback && el.rollback() //还原 ms-with ms-on
+ bindingHandlers[type](el, el.vmodels)
+ }
+ })
+ })(data)// jshint ignore:line
+ }
+ delete midway[ret.$id]
+ }
+ return ret
+ }
+ }
+
+ /*********************************************************************
+ * 监控数组(与ms-each, ms-repeat配合使用) *
+ **********************************************************************/
+
+ function Collection(model) {
+ var array = []
+ array.$id = generateID()
+ array.$model = model //数据模型
+ array.$events = {}
+ array.$events[subscribers] = []
+ array._ = modelFactory({
+ length: model.length
+ })
+ array._.$watch("length", function (a, b) {
+ array.$fire("length", a, b)
+ })
+ for (var i in EventBus) {
+ array[i] = EventBus[i]
+ }
+ array.$map = {
+ el: 1
+ }
+ array.$proxy = []
+ avalon.mix(array, CollectionPrototype)
+ return array
+ }
+
+ function mutateArray(method, pos, n, index, method2, pos2, n2) {
+ var oldLen = this.length, loop = 2
+ while (--loop) {
+ switch (method) {
+ case "add":
+ /* jshint ignore:start */
+ var m = pos + n
+ var array = this.$model.slice(pos, m).map(function (el) {
+ if (rcomplexType.test(avalon.type(el))) {//转换为VM
+ return el.$id ? el : modelFactory(el, 0, el)
+ } else {
+ return el
+ }
+ })
+ /* jshint ignore:end */
+ for (var i = pos; i < m; i++) {//生成代理VM
+ var proxy = eachProxyAgent(i, this)
+ this.$proxy.splice(i, 0, proxy)
+ }
+ _splice.apply(this, [pos, 0].concat(array))
+ this._fire("add", pos, n)
+ break
+ case "del":
+ var ret = this._splice(pos, n)
+ var removed = this.$proxy.splice(pos, n) //回收代理VM
+ recycleProxies(removed, "each")
+ this._fire("del", pos, n)
+ break
+ }
+ if (method2) {
+ method = method2
+ pos = pos2
+ n = n2
+ loop = 2
+ method2 = 0
+ }
+ }
+ resetIndex(this.$proxy, index)
+ if (this.length !== oldLen) {
+ this._.length = this.length
+ }
+ return ret
+ }
+
+ var _splice = ap.splice
+ var CollectionPrototype = {
+ _splice: _splice,
+ _fire: function (method, a, b) {
+ notifySubscribers(this.$events[subscribers], method, a, b)
+ },
+ size: function () { //取得数组长度,这个函数可以同步视图,length不能
+ return this._.length
+ },
+ pushArray: function (array) {
+ var m = array.length, n = this.length
+ if (m) {
+ ap.push.apply(this.$model, array)
+ mutateArray.call(this, "add", n, m, Math.max(0, n - 1))
+ }
+ return m + n
+ },
+ push: function () {
+ //http://jsperf.com/closure-with-arguments
+ var array = []
+ var i, n = arguments.length
+ for (i = 0; i < n; i++) {
+ array[i] = arguments[i]
+ }
+ return this.pushArray(array)
+ },
+ unshift: function () {
+ var m = arguments.length, n = this.length
+ if (m) {
+ ap.unshift.apply(this.$model, arguments)
+ mutateArray.call(this, "add", 0, m, 0)
+ }
+ return m + n //IE67的unshift不会返回长度
+ },
+ shift: function () {
+ if (this.length) {
+ var el = this.$model.shift()
+ mutateArray.call(this, "del", 0, 1, 0)
+ return el //返回被移除的元素
+ }
+ },
+ pop: function () {
+ var n = this.length
+ if (n) {
+ var el = this.$model.pop()
+ mutateArray.call(this, "del", n - 1, 1, Math.max(0, n - 2))
+ return el //返回被移除的元素
+ }
+ },
+ splice: function (start) {
+ var m = arguments.length, args = [], change
+ var removed = _splice.apply(this.$model, arguments)
+ if (removed.length) { //如果用户删掉了元素
+ args.push("del", start, removed.length, 0)
+ change = true
+ }
+ if (m > 2) { //如果用户添加了元素
+ if (change) {
+ args.splice(3, 1, 0, "add", start, m - 2)
+ } else {
+ args.push("add", start, m - 2, 0)
+ }
+ change = true
+ }
+ if (change) { //返回被移除的元素
+ return mutateArray.apply(this, args)
+ } else {
+ return []
+ }
+ },
+ contains: function (el) { //判定是否包含
+ return this.indexOf(el) !== -1
+ },
+ remove: function (el) { //移除第一个等于给定值的元素
+ return this.removeAt(this.indexOf(el))
+ },
+ removeAt: function (index) { //移除指定索引上的元素
+ if (index >= 0) {
+ this.$model.splice(index, 1)
+ return mutateArray.call(this, "del", index, 1, 0)
+ }
+ return []
+ },
+ clear: function () {
+ recycleProxies(this.$proxy, "each")
+ this.$model.length = this.$proxy.length = this.length = this._.length = 0 //清空数组
+ this._fire("clear", 0)
+ return this
+ },
+ removeAll: function (all) { //移除N个元素
+ if (Array.isArray(all)) {
+ all.forEach(function (el) {
+ this.remove(el)
+ }, this)
+ } else if (typeof all === "function") {
+ for (var i = this.length - 1; i >= 0; i--) {
+ var el = this[i]
+ if (all(el, i)) {
+ this.removeAt(i)
+ }
+ }
+ } else {
+ this.clear()
+ }
+ },
+ ensure: function (el) {
+ if (!this.contains(el)) { //只有不存在才push
+ this.push(el)
+ }
+ return this
+ },
+ set: function (index, val) {
+ if (index >= 0) {
+ var valueType = avalon.type(val)
+ if (val && val.$model) {
+ val = val.$model
+ }
+ var target = this[index]
+ if (valueType === "object") {
+ for (var i in val) {
+ if (target.hasOwnProperty(i)) {
+ target[i] = val[i]
+ }
+ }
+ } else if (valueType === "array") {
+ target.clear().push.apply(target, val)
+ } else if (target !== val) {
+ this[index] = val
+ this.$model[index] = val
+ var proxy = this.$proxy[index]
+ if (proxy) {
+ notifySubscribers(proxy.$events.el)
+ }
+ // this._fire("set", index, val)
+ }
+ }
+ return this
+ }
+ }
+//相当于原来bindingExecutors.repeat 的index分支
+ function resetIndex(array, pos) {
+ var last = array.length - 1
+ for (var el; el = array[pos]; pos++) {
+ el.$index = pos
+ el.$first = pos === 0
+ el.$last = pos === last
+ }
+ }
+
+ function sortByIndex(array, indexes) {
+ var map = {};
+ for (var i = 0, n = indexes.length; i < n; i++) {
+ map[i] = array[i] // preserve
+ var j = indexes[i]
+ if (j in map) {
+ array[i] = map[j]
+ delete map[j]
+ } else {
+ array[i] = array[j]
+ }
+ }
+ }
+
+ "sort,reverse".replace(rword, function (method) {
+ CollectionPrototype[method] = function () {
+ var newArray = this.$model//这是要排序的新数组
+ var oldArray = newArray.concat() //保持原来状态的旧数组
+ var mask = Math.random()
+ var indexes = []
+ var hasSort
+ ap[method].apply(newArray, arguments) //排序
+ for (var i = 0, n = oldArray.length; i < n; i++) {
+ var neo = newArray[i]
+ var old = oldArray[i]
+ if (isEqual(neo, old)) {
+ indexes.push(i)
+ } else {
+ var index = oldArray.indexOf(neo)
+ indexes.push(index)//得到新数组的每个元素在旧数组对应的位置
+ oldArray[index] = mask //屏蔽已经找过的元素
+ hasSort = true
+ }
+ }
+ if (hasSort) {
+ sortByIndex(this, indexes)
+ sortByIndex(this.$proxy, indexes)
+ this._fire("move", indexes)
+ resetIndex(this.$proxy, 0)
+ }
+ return this
+ }
+ })
+
+ /*********************************************************************
+ * 依赖调度系统 *
+ **********************************************************************/
+ var ronduplex = /^(duplex|on)$/
+
+ avalon.injectBinding = function (data) {
+ Registry[expose] = data //暴光此函数,方便collectSubscribers收集
+ avalon.openComputedCollect = true
+ var fn = data.evaluator
+ if (fn) { //如果是求值函数
+ try {
+ var c = ronduplex.test(data.type) ? data : fn.apply(0, data.args)
+ if (!data.noRefresh)
+ data.handler(c, data.element, data)
+ } catch (e) {
+ //log("warning:exception throwed in [avalon.injectBinding] " + e)
+ delete data.evaluator
+ var node = data.element
+ if (node.nodeType === 3) {
+ var parent = node.parentNode
+ if (kernel.commentInterpolate) {
+ parent.replaceChild(DOC.createComment(data.value), node)
+ } else {
+ node.data = openTag + data.value + closeTag
+ }
+ }
+ }
+ }
+ avalon.openComputedCollect = false
+ delete Registry[expose]
+ }
+
+ function collectSubscribers(list) { //收集依赖于这个访问器的订阅者
+ var data = Registry[expose]
+ if (list && data && avalon.Array.ensure(list, data) && data.element) { //只有数组不存在此元素才push进去
+ addSubscribers(data, list)
+ }
+ }
+
+
+ function addSubscribers(data, list) {
+ data.$uuid = data.$uuid || generateID()
+ list.$uuid = list.$uuid || generateID()
+ var obj = {
+ data: data,
+ list: list,
+ $$uuid: data.$uuid + list.$uuid
+ }
+ if (!$$subscribers[obj.$$uuid]) {
+ $$subscribers[obj.$$uuid] = 1
+ $$subscribers.push(obj)
+ }
+ }
+
+ function disposeData(data) {
+ data.element = null
+ data.rollback && data.rollback()
+ for (var key in data) {
+ data[key] = null
+ }
+ }
+
+ function isRemove(el) {
+ try {//IE下,如果文本节点脱离DOM树,访问parentNode会报错
+ if (!el.parentNode) {
+ return true
+ }
+ } catch (e) {
+ return true
+ }
+ return el.msRetain ? 0 : (el.nodeType === 1 ? typeof el.sourceIndex === "number" ?
+ el.sourceIndex === 0 : !root.contains(el) : !avalon.contains(root, el))
+ }
+
+ var $$subscribers = avalon.$$subscribers = []
+ var beginTime = new Date()
+ var oldInfo = {}
+
+ function removeSubscribers() {
+ var i = $$subscribers.length
+ var n = i
+ var k = 0
+ var obj
+ var types = []
+ var newInfo = {}
+ var needTest = {}
+ while (obj = $$subscribers[--i]) {
+ var data = obj.data
+ var type = data.type
+ if (newInfo[type]) {
+ newInfo[type]++
+ } else {
+ newInfo[type] = 1
+ types.push(type)
+ }
+ }
+ var diff = false
+ types.forEach(function (type) {
+ if (oldInfo[type] !== newInfo[type]) {
+ needTest[type] = 1
+ diff = true
+ }
+ })
+ i = n
+ //avalon.log("需要检测的个数 " + i)
+ if (diff) {
+ //avalon.log("有需要移除的元素")
+ while (obj = $$subscribers[--i]) {
+ data = obj.data
+ if (data.element === void 0)
+ continue
+ if (needTest[data.type] && isRemove(data.element)) { //如果它没有在DOM树
+ k++
+ $$subscribers.splice(i, 1)
+ delete $$subscribers[obj.$$uuid]
+ avalon.Array.remove(obj.list, data)
+ //log("debug: remove " + data.type)
+ disposeData(data)
+ obj.data = obj.list = null
+ }
+ }
+ }
+ oldInfo = newInfo
+ // avalon.log("已经移除的个数 " + k)
+ beginTime = new Date()
+ }
+
+ function notifySubscribers(list) { //通知依赖于这个访问器的订阅者更新自身
+ if (list && list.length) {
+ if (new Date() - beginTime > 444 && typeof list[0] === "object") {
+ removeSubscribers()
+ }
+ var args = aslice.call(arguments, 1)
+ for (var i = list.length, fn; fn = list[--i];) {
+ var el = fn.element
+ if (el && el.parentNode) {
+ if (fn.$repeat) {
+ fn.handler.apply(fn, args) //处理监控数组的方法
+ } else if (fn.type !== "on") { //事件绑定只能由用户触发,不能由程序触发
+ var fun = fn.evaluator || noop
+ fn.handler(fun.apply(0, fn.args || []), el, fn)
+ }
+ }
+ }
+ }
+ }
+
+ /************************************************************************
+ * HTML处理(parseHTML, innerHTML, clearHTML) *
+ **************************************************************************/
+//parseHTML的辅助变量
+ var tagHooks = new function () {// jshint ignore:line
+ avalon.mix(this, {
+ option: DOC.createElement("select"),
+ thead: DOC.createElement("table"),
+ td: DOC.createElement("tr"),
+ area: DOC.createElement("map"),
+ tr: DOC.createElement("tbody"),
+ col: DOC.createElement("colgroup"),
+ legend: DOC.createElement("fieldset"),
+ _default: DOC.createElement("div"),
+ "g": DOC.createElementNS("http://www.w3.org/2000/svg", "svg")
+ })
+ this.optgroup = this.option
+ this.tbody = this.tfoot = this.colgroup = this.caption = this.thead
+ this.th = this.td
+ }// jshint ignore:line
+
+ String("circle,defs,ellipse,image,line,path,polygon,polyline,rect,symbol,text,use").replace(rword, function (tag) {
+ tagHooks[tag] = tagHooks.g //处理SVG
+ })
+ var rtagName = /<([\w:]+)/
+ var rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig
+ var scriptTypes = oneObject(["", "text/javascript", "text/ecmascript", "application/ecmascript", "application/javascript"])
+ var script = DOC.createElement("script")
+ var rhtml = /<|&#?\w+;/
+ avalon.parseHTML = function (html) {
+ var fragment = hyperspace.cloneNode(false)
+ if (typeof html !== "string") {
+ return fragment
+ }
+ if (!rhtml.test(html)) {
+ fragment.appendChild(DOC.createTextNode(html))
+ return fragment
+ }
+ html = html.replace(rxhtml, "<$1></$2>").trim()
+ var tag = (rtagName.exec(html) || ["", ""])[1].toLowerCase(),
+ //取得其标签名
+ wrapper = tagHooks[tag] || tagHooks._default,
+ firstChild
+ wrapper.innerHTML = html
+ var els = wrapper.getElementsByTagName("script")
+ if (els.length) { //使用innerHTML生成的script节点不会发出请求与执行text属性
+ for (var i = 0, el; el = els[i++];) {
+ if (scriptTypes[el.type]) {
+ var neo = script.cloneNode(false) //FF不能省略参数
+ ap.forEach.call(el.attributes, function (attr) {
+ neo.setAttribute(attr.name, attr.value)
+ })// jshint ignore:line
+ neo.text = el.text
+ el.parentNode.replaceChild(neo, el)
+ }
+ }
+ }
+
+ while (firstChild = wrapper.firstChild) { // 将wrapper上的节点转移到文档碎片上!
+ fragment.appendChild(firstChild)
+ }
+ return fragment
+ }
+
+ avalon.innerHTML = function (node, html) {
+ var a = this.parseHTML(html)
+ this.clearHTML(node).appendChild(a)
+ }
+
+ avalon.clearHTML = function (node) {
+ node.textContent = ""
+ while (node.firstChild) {
+ node.removeChild(node.firstChild)
+ }
+ return node
+ }
+
+ /*********************************************************************
+ * 扫描系统 *
+ **********************************************************************/
+
+ avalon.scan = function (elem, vmodel) {
+ elem = elem || root
+ var vmodels = vmodel ? [].concat(vmodel) : []
+ scanTag(elem, vmodels)
+ }
+
+//http://www.w3.org/TR/html5/syntax.html#void-elements
+ var stopScan = oneObject("area,base,basefont,br,col,command,embed,hr,img,input,link,meta,param,source,track,wbr,noscript,script,style,textarea".toUpperCase())
+
+ function checkScan(elem, callback, innerHTML) {
+ var id = setTimeout(function () {
+ var currHTML = elem.innerHTML
+ clearTimeout(id)
+ if (currHTML === innerHTML) {
+ callback()
+ } else {
+ checkScan(elem, callback, currHTML)
+ }
+ })
+ }
+
+
+ function createSignalTower(elem, vmodel) {
+ var id = elem.getAttribute("avalonctrl") || vmodel.$id
+ elem.setAttribute("avalonctrl", id)
+ vmodel.$events.expr = elem.tagName + '[avalonctrl="' + id + '"]'
+ }
+
+ var getBindingCallback = function (elem, name, vmodels) {
+ var callback = elem.getAttribute(name)
+ if (callback) {
+ for (var i = 0, vm; vm = vmodels[i++];) {
+ if (vm.hasOwnProperty(callback) && typeof vm[callback] === "function") {
+ return vm[callback]
+ }
+ }
+ }
+ }
+
+ function executeBindings(bindings, vmodels) {
+ for (var i = 0, data; data = bindings[i++];) {
+ data.vmodels = vmodels
+ bindingHandlers[data.type](data, vmodels)
+ if (data.evaluator && data.element && data.element.nodeType === 1) { //移除数据绑定,防止被二次解析
+ //chrome使用removeAttributeNode移除不存在的特性节点时会报错 https://github.com/RubyLouvre/avalon/issues/99
+ data.element.removeAttribute(data.name)
+ }
+ }
+ bindings.length = 0
+ }
+
+//https://github.com/RubyLouvre/avalon/issues/636
+ var mergeTextNodes = IEVersion && window.MutationObserver ? function (elem) {
+ var node = elem.firstChild, text
+ while (node) {
+ var aaa = node.nextSibling
+ if (node.nodeType === 3) {
+ if (text) {
+ text.nodeValue += node.nodeValue
+ elem.removeChild(node)
+ } else {
+ text = node
+ }
+ } else {
+ text = null
+ }
+ node = aaa
+ }
+ } : 0
+
+ var rmsAttr = /ms-(\w+)-?(.*)/
+ var priorityMap = {
+ "if": 10,
+ "repeat": 90,
+ "data": 100,
+ "widget": 110,
+ "each": 1400,
+ "with": 1500,
+ "duplex": 2000,
+ "on": 3000
+ }
+
+ var events = oneObject("animationend,blur,change,input,click,dblclick,focus,keydown,keypress,keyup,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,scan,scroll,submit")
+ var obsoleteAttrs = oneObject("value,title,alt,checked,selected,disabled,readonly,enabled")
+
+ function bindingSorter(a, b) {
+ return a.priority - b.priority
+ }
+
+ function scanAttr(elem, vmodels) {
+ //防止setAttribute, removeAttribute时 attributes自动被同步,导致for循环出错
+ var attributes = elem.hasAttributes() ? avalon.slice(elem.attributes) : []
+ var bindings = [],
+ msData = createMap(),
+ match
+ for (var i = 0, attr; attr = attributes[i++];) {
+ if (attr.specified) {
+ if (match = attr.name.match(rmsAttr)) {
+ //如果是以指定前缀命名的
+ var type = match[1]
+ var param = match[2] || ""
+ var value = attr.value
+ var name = attr.name
+ msData[name] = value
+ if (events[type]) {
+ param = type
+ type = "on"
+ } else if (obsoleteAttrs[type]) {
+ log("warning!请改用ms-attr-" + type + "代替ms-" + type + "!")
+ if (type === "enabled") {//吃掉ms-enabled绑定,用ms-disabled代替
+ log("warning!ms-enabled或ms-attr-enabled已经被废弃")
+ type = "disabled"
+ value = "!(" + value + ")"
+ }
+ param = type
+ type = "attr"
+ elem.removeAttribute(name)
+ name = "ms-attr-" + param
+ elem.setAttribute(name, value)
+ match = [name]
+ msData[name] = value
+ }
+ if (typeof bindingHandlers[type] === "function") {
+ var binding = {
+ type: type,
+ param: param,
+ element: elem,
+ name: match[0],
+ value: value,
+ priority: type in priorityMap ? priorityMap[type] : type.charCodeAt(0) * 10 + (Number(param) || 0)
+ }
+ if (type === "html" || type === "text") {
+ var token = getToken(value)
+ avalon.mix(binding, token)
+ binding.filters = binding.filters.replace(rhasHtml, function () {
+ binding.type = "html"
+ binding.group = 1
+ return ""
+ })// jshint ignore:line
+ }
+ if (name === "ms-if-loop") {
+ binding.priority += 100
+ }
+ if (vmodels.length) {
+ bindings.push(binding)
+ if (type === "widget") {
+ elem.msData = elem.msData || msData
+ }
+ }
+ }
+ }
+ }
+ }
+ var control = elem.type
+ if (control && msData["ms-duplex"]) {
+ if (msData["ms-attr-checked"] && /radio|checkbox/.test(control)) {
+ log("warning!" + control + "控件不能同时定义ms-attr-checked与ms-duplex")
+ }
+ if (msData["ms-attr-value"] && /text|password/.test(control)) {
+ log("warning!" + control + "控件不能同时定义ms-attr-value与ms-duplex")
+ }
+ }
+ bindings.sort(bindingSorter)
+ var scanNode = true
+ for (i = 0; binding = bindings[i]; i++) {
+ type = binding.type
+ if (rnoscanAttrBinding.test(type)) {
+ return executeBindings(bindings.slice(0, i + 1), vmodels)
+ } else if (scanNode) {
+ scanNode = !rnoscanNodeBinding.test(type)
+ }
+ }
+ executeBindings(bindings, vmodels)
+ if (scanNode && !stopScan[elem.tagName] && rbind.test(elem.innerHTML + elem.textContent)) {
+ mergeTextNodes && mergeTextNodes(elem)
+ scanNodeList(elem, vmodels) //扫描子孙元素
+ }
+ }
+
+ var rnoscanAttrBinding = /^if|widget|repeat$/
+ var rnoscanNodeBinding = /^each|with|html|include$/
+
+ function scanNodeList(parent, vmodels) {
+ var node = parent.firstChild
+ while (node) {
+ var nextNode = node.nextSibling
+ scanNode(node, node.nodeType, vmodels)
+ node = nextNode
+ }
+ }
+
+ function scanNodeArray(nodes, vmodels) {
+ for (var i = 0, node; node = nodes[i++];) {
+ scanNode(node, node.nodeType, vmodels)
+ }
+ }
+
+ function scanNode(node, nodeType, vmodels) {
+ if (nodeType === 1) {
+ scanTag(node, vmodels) //扫描元素节点
+ if (node.msCallback) {
+ node.msCallback()
+ node.msCallback = void 0
+ }
+ } else if (nodeType === 3 && rexpr.test(node.data)) {
+ scanText(node, vmodels) //扫描文本节点
+ } else if (kernel.commentInterpolate && nodeType === 8 && !rexpr.test(node.nodeValue)) {
+ scanText(node, vmodels) //扫描注释节点
+ }
+ }
+
+ function scanTag(elem, vmodels, node) {
+ //扫描顺序 ms-skip(0) --> ms-important(1) --> ms-controller(2) --> ms-if(10) --> ms-repeat(100)
+ //--> ms-if-loop(110) --> ms-attr(970) ...--> ms-each(1400)-->ms-with(1500)--〉ms-duplex(2000)垫后
+ var a = elem.getAttribute("ms-skip")
+ var b = elem.getAttributeNode("ms-important")
+ var c = elem.getAttributeNode("ms-controller")
+ if (typeof a === "string") {
+ return
+ } else if (node = b || c) {
+ var newVmodel = avalon.vmodels[node.value]
+ if (!newVmodel) {
+ return
+ }
+ //ms-important不包含父VM,ms-controller相反
+ vmodels = node === b ? [newVmodel] : [newVmodel].concat(vmodels)
+ elem.removeAttribute(node.name) //removeAttributeNode不会刷新[ms-controller]样式规则
+ elem.classList.remove(node.name)
+ createSignalTower(elem, newVmodel)
+ }
+ scanAttr(elem, vmodels) //扫描特性节点
+ }
+
+ var rhasHtml = /\|\s*html\s*/,
+ r11a = /\|\|/g,
+ rlt = /</g,
+ rgt = />/g,
+ rstringLiteral = /(['"])(\\\1|.)+?\1/g
+
+ function getToken(value) {
+ if (value.indexOf("|") > 0) {
+ var scapegoat = value.replace(rstringLiteral, function (_) {
+ return Array(_.length + 1).join("1")// jshint ignore:line
+ })
+ var index = scapegoat.replace(r11a, "\u1122\u3344").indexOf("|") //干掉所有短路或
+ if (index > -1) {
+ return {
+ filters: value.slice(index),
+ value: value.slice(0, index),
+ expr: true
+ }
+ }
+ }
+ return {
+ value: value,
+ filters: "",
+ expr: true
+ }
+ }
+
+ function scanExpr(str) {
+ var tokens = [],
+ value, start = 0,
+ stop
+ do {
+ stop = str.indexOf(openTag, start)
+ if (stop === -1) {
+ break
+ }
+ value = str.slice(start, stop)
+ if (value) { // {{ 左边的文本
+ tokens.push({
+ value: value,
+ filters: "",
+ expr: false
+ })
+ }
+ start = stop + openTag.length
+ stop = str.indexOf(closeTag, start)
+ if (stop === -1) {
+ break
+ }
+ value = str.slice(start, stop)
+ if (value) { //处理{{ }}插值表达式
+ tokens.push(getToken(value))
+ }
+ start = stop + closeTag.length
+ } while (1)
+ value = str.slice(start)
+ if (value) { //}} 右边的文本
+ tokens.push({
+ value: value,
+ expr: false,
+ filters: ""
+ })
+ }
+ return tokens
+ }
+
+ function scanText(textNode, vmodels) {
+ var bindings = []
+ if (textNode.nodeType === 8) {
+ var token = getToken(textNode.nodeValue)
+ var tokens = [token]
+ } else {
+ tokens = scanExpr(textNode.data)
+ }
+ if (tokens.length) {
+ for (var i = 0; token = tokens[i++];) {
+ var node = DOC.createTextNode(token.value) //将文本转换为文本节点,并替换原来的文本节点
+ if (token.expr) {
+ token.type = "text"
+ token.element = node
+ token.filters = token.filters.replace(rhasHtml, function () {
+ token.type = "html"
+ token.group = 1
+ return ""
+ })// jshint ignore:line
+ bindings.push(token) //收集带有插值表达式的文本
+ }
+ hyperspace.appendChild(node)
+ }
+ textNode.parentNode.replaceChild(hyperspace, textNode)
+ if (bindings.length)
+ executeBindings(bindings, vmodels)
+ }
+ }
+
+ /*********************************************************************
+ * avalon的原型方法定义区 *
+ **********************************************************************/
+
+ function hyphen(target) {
+ //转换为连字符线风格
+ return target.replace(/([a-z\d])([A-Z]+)/g, "$1-$2").toLowerCase()
+ }
+
+ function camelize(target) {
+ //转换为驼峰风格
+ if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
+ return target //提前判断,提高getStyle等的效率
+ }
+ return target.replace(/[-_][^-_]/g, function (match) {
+ return match.charAt(1).toUpperCase()
+ })
+ }
+
+ "add,remove".replace(rword, function (method) {
+ avalon.fn[method + "Class"] = function (cls) {
+ var el = this[0]
+ //https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
+ if (cls && typeof cls === "string" && el && el.nodeType === 1) {
+ cls.replace(/\S+/g, function (c) {
+ el.classList[method](c)
+ })
+ }
+ return this
+ }
+ })
+
+ avalon.fn.mix({
+ hasClass: function (cls) {
+ var el = this[0] || {} //IE10+, chrome8+, firefox3.6+, safari5.1+,opera11.5+支持classList,chrome24+,firefox26+支持classList2.0
+ return el.nodeType === 1 && el.classList.contains(cls)
+ },
+ toggleClass: function (value, stateVal) {
+ var className, i = 0
+ var classNames = String(value).split(/\s+/)
+ var isBool = typeof stateVal === "boolean"
+ while ((className = classNames[i++])) {
+ var state = isBool ? stateVal : !this.hasClass(className)
+ this[state ? "addClass" : "removeClass"](className)
+ }
+ return this
+ },
+ attr: function (name, value) {
+ if (arguments.length === 2) {
+ this[0].setAttribute(name, value)
+ return this
+ } else {
+ return this[0].getAttribute(name)
+ }
+ },
+ data: function (name, value) {
+ name = "data-" + hyphen(name || "")
+ switch (arguments.length) {
+ case 2:
+ this.attr(name, value)
+ return this
+ case 1:
+ var val = this.attr(name)
+ return parseData(val)
+ case 0:
+ var ret = {}
+ ap.forEach.call(this[0].attributes, function (attr) {
+ if (attr) {
+ name = attr.name
+ if (!name.indexOf("data-")) {
+ name = camelize(name.slice(5))
+ ret[name] = parseData(attr.value)
+ }
+ }
+ })
+ return ret
+ }
+ },
+ removeData: function (name) {
+ name = "data-" + hyphen(name)
+ this[0].removeAttribute(name)
+ return this
+ },
+ css: function (name, value) {
+ if (avalon.isPlainObject(name)) {
+ for (var i in name) {
+ avalon.css(this, i, name[i])
+ }
+ } else {
+ var ret = avalon.css(this, name, value)
+ }
+ return ret !== void 0 ? ret : this
+ },
+ position: function () {
+ var offsetParent, offset,
+ elem = this[0],
+ parentOffset = {
+ top: 0,
+ left: 0
+ };
+ if (!elem) {
+ return
+ }
+ if (this.css("position") === "fixed") {
+ offset = elem.getBoundingClientRect()
+ } else {
+ offsetParent = this.offsetParent() //得到真正的offsetParent
+ offset = this.offset() // 得到正确的offsetParent
+ if (offsetParent[0].tagName !== "HTML") {
+ parentOffset = offsetParent.offset()
+ }
+ parentOffset.top += avalon.css(offsetParent[0], "borderTopWidth", true)
+ parentOffset.left += avalon.css(offsetParent[0], "borderLeftWidth", true)
+ // Subtract offsetParent scroll positions
+ parentOffset.top -= offsetParent.scrollTop()
+ parentOffset.left -= offsetParent.scrollLeft()
+ }
+ return {
+ top: offset.top - parentOffset.top - avalon.css(elem, "marginTop", true),
+ left: offset.left - parentOffset.left - avalon.css(elem, "marginLeft", true)
+ }
+ },
+ offsetParent: function () {
+ var offsetParent = this[0].offsetParent
+ while (offsetParent && avalon.css(offsetParent, "position") === "static") {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return avalon(offsetParent || root)
+ },
+ bind: function (type, fn, phase) {
+ if (this[0]) { //此方法不会链
+ return avalon.bind(this[0], type, fn, phase)
+ }
+ },
+ unbind: function (type, fn, phase) {
+ if (this[0]) {
+ avalon.unbind(this[0], type, fn, phase)
+ }
+ return this
+ },
+ val: function (value) {
+ var node = this[0]
+ if (node && node.nodeType === 1) {
+ var get = arguments.length === 0
+ var access = get ? ":get" : ":set"
+ var fn = valHooks[getValType(node) + access]
+ if (fn) {
+ var val = fn(node, value)
+ } else if (get) {
+ return (node.value || "").replace(/\r/g, "")
+ } else {
+ node.value = value
+ }
+ }
+ return get ? val : this
+ }
+ })
+
+ if (root.dataset) {
+ avalon.fn.data = function (name, val) {
+ name = name && camelize(name)
+ var dataset = this[0].dataset
+ switch (arguments.length) {
+ case 2:
+ dataset[name] = val
+ return this
+ case 1:
+ val = dataset[name]
+ return parseData(val)
+ case 0:
+ var ret = createMap()
+ for (name in dataset) {
+ ret[name] = parseData(dataset[name])
+ }
+ return ret
+ }
+ }
+ }
+ var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/
+ avalon.parseJSON = JSON.parse
+
+ function parseData(data) {
+ try {
+ if (typeof data === "object")
+ return data
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null : +data + "" === data ? +data : rbrace.test(data) ? JSON.parse(data) : data
+ } catch (e) {
+ }
+ return data
+ }
+
+ avalon.each({
+ scrollLeft: "pageXOffset",
+ scrollTop: "pageYOffset"
+ }, function (method, prop) {
+ avalon.fn[method] = function (val) {
+ var node = this[0] || {}, win = getWindow(node),
+ top = method === "scrollTop"
+ if (!arguments.length) {
+ return win ? win[prop] : node[method]
+ } else {
+ if (win) {
+ win.scrollTo(!top ? val : win[prop], top ? val : win[prop])
+ } else {
+ node[method] = val
+ }
+ }
+ }
+ })
+
+ function getWindow(node) {
+ return node.window && node.document ? node : node.nodeType === 9 ? node.defaultView : false
+ }
+
+//=============================css相关==================================
+ var cssHooks = avalon.cssHooks = createMap()
+ var prefixes = ["", "-webkit-", "-moz-", "-ms-"] //去掉opera-15的支持
+ var cssMap = {
+ "float": "cssFloat"
+ }
+ avalon.cssNumber = oneObject("columnCount,order,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom")
+
+ avalon.cssName = function (name, host, camelCase) {
+ if (cssMap[name]) {
+ return cssMap[name]
+ }
+ host = host || root.style
+ for (var i = 0, n = prefixes.length; i < n; i++) {
+ camelCase = camelize(prefixes[i] + name)
+ if (camelCase in host) {
+ return (cssMap[name] = camelCase)
+ }
+ }
+ return null
+ }
+ cssHooks["@:set"] = function (node, name, value) {
+ node.style[name] = value
+ }
+
+ cssHooks["@:get"] = function (node, name) {
+ if (!node || !node.style) {
+ throw new Error("getComputedStyle要求传入一个节点 " + node)
+ }
+ var ret, computed = getComputedStyle(node)
+ if (computed) {
+ ret = name === "filter" ? computed.getPropertyValue(name) : computed[name]
+ if (ret === "") {
+ ret = node.style[name] //其他浏览器需要我们手动取内联样式
+ }
+ }
+ return ret
+ }
+ cssHooks["opacity:get"] = function (node) {
+ var ret = cssHooks["@:get"](node, "opacity")
+ return ret === "" ? "1" : ret
+ }
+
+ "top,left".replace(rword, function (name) {
+ cssHooks[name + ":get"] = function (node) {
+ var computed = cssHooks["@:get"](node, name)
+ return /px$/.test(computed) ? computed :
+ avalon(node).position()[name] + "px"
+ }
+ })
+ var cssShow = {
+ position: "absolute",
+ visibility: "hidden",
+ display: "block"
+ }
+ var rdisplayswap = /^(none|table(?!-c[ea]).+)/
+
+ function showHidden(node, array) {
+ //http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
+ if (node.offsetWidth <= 0) { //opera.offsetWidth可能小于0
+ var styles = getComputedStyle(node, null)
+ if (rdisplayswap.test(styles["display"])) {
+ var obj = {
+ node: node
+ }
+ for (var name in cssShow) {
+ obj[name] = styles[name]
+ node.style[name] = cssShow[name]
+ }
+ array.push(obj)
+ }
+ var parent = node.parentNode
+ if (parent && parent.nodeType === 1) {
+ showHidden(parent, array)
+ }
+ }
+ }
+
+ "Width,Height".replace(rword, function (name) { //fix 481
+ var method = name.toLowerCase(),
+ clientProp = "client" + name,
+ scrollProp = "scroll" + name,
+ offsetProp = "offset" + name
+ cssHooks[method + ":get"] = function (node, which, override) {
+ var boxSizing = -4
+ if (typeof override === "number") {
+ boxSizing = override
+ }
+ which = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"]
+ var ret = node[offsetProp] // border-box 0
+ if (boxSizing === 2) { // margin-box 2
+ return ret + avalon.css(node, "margin" + which[0], true) + avalon.css(node, "margin" + which[1], true)
+ }
+ if (boxSizing < 0) { // padding-box -2
+ ret = ret - avalon.css(node, "border" + which[0] + "Width", true) - avalon.css(node, "border" + which[1] + "Width", true)
+ }
+ if (boxSizing === -4) { // content-box -4
+ ret = ret - avalon.css(node, "padding" + which[0], true) - avalon.css(node, "padding" + which[1], true)
+ }
+ return ret
+ }
+ cssHooks[method + "&get"] = function (node) {
+ var hidden = [];
+ showHidden(node, hidden);
+ var val = cssHooks[method + ":get"](node)
+ for (var i = 0, obj; obj = hidden[i++];) {
+ node = obj.node
+ for (var n in obj) {
+ if (typeof obj[n] === "string") {
+ node.style[n] = obj[n]
+ }
+ }
+ }
+ return val;
+ }
+ avalon.fn[method] = function (value) { //会忽视其display
+ var node = this[0]
+ if (arguments.length === 0) {
+ if (node.setTimeout) { //取得窗口尺寸,IE9后可以用node.innerWidth /innerHeight代替
+ return node["inner" + name]
+ }
+ if (node.nodeType === 9) { //取得页面尺寸
+ var doc = node.documentElement
+ //FF chrome html.scrollHeight< body.scrollHeight
+ //IE 标准模式 : html.scrollHeight> body.scrollHeight
+ //IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
+ return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp])
+ }
+ return cssHooks[method + "&get"](node)
+ } else {
+ return this.css(method, value)
+ }
+ }
+ avalon.fn["inner" + name] = function () {
+ return cssHooks[method + ":get"](this[0], void 0, -2)
+ }
+ avalon.fn["outer" + name] = function (includeMargin) {
+ return cssHooks[method + ":get"](this[0], void 0, includeMargin === true ? 2 : 0)
+ }
+ })
+ avalon.fn.offset = function () { //取得距离页面左右角的坐标
+ var node = this[0]
+ try {
+ var rect = node.getBoundingClientRect()
+ // Make sure element is not hidden (display: none) or disconnected
+ // https://github.com/jquery/jquery/pull/2043/files#r23981494
+ if (rect.width || rect.height || node.getClientRects().length) {
+ var doc = node.ownerDocument
+ var root = doc.documentElement
+ var win = doc.defaultView
+ return {
+ top: rect.top + win.pageYOffset - root.clientTop,
+ left: rect.left + win.pageXOffset - root.clientLeft
+ }
+ }
+ } catch (e) {
+ return {
+ left: 0,
+ top: 0
+ }
+ }
+ }
+ //=============================val相关=======================
+
+ function getValType(elem) {
+ var ret = elem.tagName.toLowerCase()
+ return ret === "input" && /checkbox|radio/.test(elem.type) ? "checked" : ret
+ }
+
+ var valHooks = {
+ "select:get": function (node, value) {
+ var option, options = node.options,
+ index = node.selectedIndex,
+ one = node.type === "select-one" || index < 0,
+ values = one ? null : [],
+ max = one ? index + 1 : options.length,
+ i = index < 0 ? max : one ? index : 0
+ for (; i < max; i++) {
+ option = options[i]
+ //旧式IE在reset后不会改变selected,需要改用i === index判定
+ //我们过滤所有disabled的option元素,但在safari5下,如果设置select为disable,那么其所有孩子都disable
+ //因此当一个元素为disable,需要检测其是否显式设置了disable及其父节点的disable情况
+ if ((option.selected || i === index) && !option.disabled) {
+ value = option.value
+ if (one) {
+ return value
+ }
+ //收集所有selected值组成数组返回
+ values.push(value)
+ }
+ }
+ return values
+ },
+ "select:set": function (node, values, optionSet) {
+ values = [].concat(values) //强制转换为数组
+ for (var i = 0, el; el = node.options[i++];) {
+ if ((el.selected = values.indexOf(el.value) > -1)) {
+ optionSet = true
+ }
+ }
+ if (!optionSet) {
+ node.selectedIndex = -1
+ }
+ }
+ }
+ /*********************************************************************
+ * 编译系统 *
+ **********************************************************************/
+ var quote = JSON.stringify
+
+ var keywords = [
+ "break,case,catch,continue,debugger,default,delete,do,else,false",
+ "finally,for,function,if,in,instanceof,new,null,return,switch,this",
+ "throw,true,try,typeof,var,void,while,with", /* 关键字*/
+ "abstract,boolean,byte,char,class,const,double,enum,export,extends",
+ "final,float,goto,implements,import,int,interface,long,native",
+ "package,private,protected,public,short,static,super,synchronized",
+ "throws,transient,volatile", /*保留字*/
+ "arguments,let,yield,undefined" /* ECMA 5 - use strict*/].join(",")
+ var rrexpstr = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g
+ var rsplit = /[^\w$]+/g
+ var rkeywords = new RegExp(["\\b" + keywords.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g')
+ var rnumber = /\b\d[^,]*/g
+ var rcomma = /^,+|,+$/g
+ var cacheVars = new Cache(512)
+ var getVariables = function (code) {
+ var key = "," + code.trim()
+ var ret = cacheVars.get(key)
+ if (ret) {
+ return ret
+ }
+ var match = code
+ .replace(rrexpstr, "")
+ .replace(rsplit, ",")
+ .replace(rkeywords, "")
+ .replace(rnumber, "")
+ .replace(rcomma, "")
+ .split(/^$|,+/)
+ return cacheVars.put(key, uniqSet(match))
+ }
+ /*添加赋值语句*/
+
+ function addAssign(vars, scope, name, data) {
+ var ret = [],
+ prefix = " = " + name + "."
+ var isProxy = /\$proxy\$each/.test(scope.$id)
+ for (var i = vars.length, prop; prop = vars[--i];) {
+ var el = isProxy && scope.$map[prop] ? "el" : prop
+ if (scope.hasOwnProperty(el)) {
+ ret.push(prop + prefix + el)
+ data.vars.push(prop)
+ if (data.type === "duplex") {
+ vars.get = name + "." + el
+ }
+ vars.splice(i, 1)
+ }
+ }
+ return ret
+ }
+
+ function uniqSet(array) {
+ var ret = [],
+ unique = {}
+ for (var i = 0; i < array.length; i++) {
+ var el = array[i]
+ var id = el && typeof el.$id === "string" ? el.$id : el
+ if (!unique[id]) {
+ unique[id] = ret.push(el)
+ }
+ }
+ return ret
+ }
+
+//缓存求值函数,以便多次利用
+ var cacheExprs = new Cache(128)
+//取得求值函数及其传参
+ var rduplex = /\w\[.*\]|\w\.\w/
+ var rproxy = /(\$proxy\$[a-z]+)\d+$/
+ var rthimRightParentheses = /\)\s*$/
+ var rthimOtherParentheses = /\)\s*\|/g
+ var rquoteFilterName = /\|\s*([$\w]+)/g
+ var rpatchBracket = /"\s*\["/g
+ var rthimLeftParentheses = /"\s*\(/g
+
+ function parseFilter(val, filters) {
+ filters = filters
+ .replace(rthimRightParentheses, "")//处理最后的小括号
+ .replace(rthimOtherParentheses, function () {//处理其他小括号
+ return "],|"
+ })
+ .replace(rquoteFilterName, function (a, b) { //处理|及它后面的过滤器的名字
+ return "[" + quote(b)
+ })
+ .replace(rpatchBracket, function () {
+ return '"],["'
+ })
+ .replace(rthimLeftParentheses, function () {
+ return '",'
+ }) + "]"
+ return "return avalon.filters.$filter(" + val + ", " + filters + ")"
+ }
+
+ function parseExpr(code, scopes, data) {
+ var dataType = data.type
+ var filters = data.filters || ""
+ var exprId = scopes.map(function (el) {
+ return String(el.$id).replace(rproxy, "$1")
+ }) + code + dataType + filters
+ var vars = getVariables(code).concat(),
+ assigns = [],
+ names = [],
+ args = [],
+ prefix = ""
+ //args 是一个对象数组, names 是将要生成的求值函数的参数
+ scopes = uniqSet(scopes)
+ data.vars = []
+ for (var i = 0, sn = scopes.length; i < sn; i++) {
+ if (vars.length) {
+ var name = "vm" + expose + "_" + i
+ names.push(name)
+ args.push(scopes[i])
+ assigns.push.apply(assigns, addAssign(vars, scopes[i], name, data))
+ }
+ }
+ if (!assigns.length && dataType === "duplex") {
+ return
+ }
+ if (dataType !== "duplex" && (code.indexOf("||") > -1 || code.indexOf("&&") > -1)) {
+ //https://github.com/RubyLouvre/avalon/issues/583
+ data.vars.forEach(function (v) {
+ var reg = new RegExp("\\b" + v + "(?:\\.\\w+|\\[\\w+\\])+", "ig")
+ code = code.replace(reg, function (_) {
+ var c = _.charAt(v.length)
+ var r = IEVersion ? code.slice(arguments[1] + _.length) : RegExp.rightContext
+ var method = /^\s*\(/.test(r)
+ if (c === "." || c === "[" || method) {//比如v为aa,我们只匹配aa.bb,aa[cc],不匹配aaa.xxx
+ var name = "var" + String(Math.random()).replace(/^0\./, "")
+ if (method) {//array.size()
+ var array = _.split(".")
+ if (array.length > 2) {
+ var last = array.pop()
+ assigns.push(name + " = " + array.join("."))
+ return name + "." + last
+ } else {
+ return _
+ }
+ }
+ assigns.push(name + " = " + _)
+ return name
+ } else {
+ return _
+ }
+ })
+ })
+ }
+ //---------------args----------------
+ data.args = args
+ //---------------cache----------------
+ var fn = cacheExprs.get(exprId) //直接从缓存,免得重复生成
+ if (fn) {
+ data.evaluator = fn
+ return
+ }
+ prefix = assigns.join(", ")
+ if (prefix) {
+ prefix = "var " + prefix
+ }
+ if (/\S/.test(filters)) { //文本绑定,双工绑定才有过滤器
+ if (!/text|html/.test(data.type)) {
+ throw Error("ms-" + data.type + "不支持过滤器")
+ }
+ code = "\nvar ret" + expose + " = " + code + ";\r\n"
+ code += parseFilter("ret" + expose, filters)
+ } else if (dataType === "duplex") { //双工绑定
+ var _body = "'use strict';\nreturn function(vvv){\n\t" +
+ prefix +
+ ";\n\tif(!arguments.length){\n\t\treturn " +
+ code +
+ "\n\t}\n\t" + (!rduplex.test(code) ? vars.get : code) +
+ "= vvv;\n} "
+ try {
+ fn = Function.apply(noop, names.concat(_body))
+ data.evaluator = cacheExprs.put(exprId, fn)
+ } catch (e) {
+ log("debug: parse error," + e.message)
+ }
+ return
+ } else if (dataType === "on") { //事件绑定
+ if (code.indexOf("(") === -1) {
+ code += ".call(this, $event)"
+ } else {
+ code = code.replace("(", ".call(this,")
+ }
+ names.push("$event")
+ code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
+ var lastIndex = code.lastIndexOf("\nreturn")
+ var header = code.slice(0, lastIndex)
+ var footer = code.slice(lastIndex)
+ code = header + "\n" + footer
+ } else { //其他绑定
+ code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
+ }
+ try {
+ fn = Function.apply(noop, names.concat("'use strict';\n" + prefix + code))
+ data.evaluator = cacheExprs.put(exprId, fn)
+ } catch (e) {
+ log("debug: parse error," + e.message)
+ } finally {
+ vars = assigns = names = null //释放内存
+ }
+ }
+
+
+//parseExpr的智能引用代理
+
+ function parseExprProxy(code, scopes, data, tokens, noRegister) {
+ if (Array.isArray(tokens)) {
+ code = tokens.map(function (el) {
+ return el.expr ? "(" + el.value + ")" : quote(el.value)
+ }).join(" + ")
+ }
+ parseExpr(code, scopes, data)
+ if (data.evaluator && !noRegister) {
+ data.handler = bindingExecutors[data.handlerName || data.type]
+ //方便调试
+ //这里非常重要,我们通过判定视图刷新函数的element是否在DOM树决定
+ //将它移出订阅者列表
+ avalon.injectBinding(data)
+ }
+ }
+
+ avalon.parseExprProxy = parseExprProxy
+ var bools = ["autofocus,autoplay,async,allowTransparency,checked,controls",
+ "declare,disabled,defer,defaultChecked,defaultSelected",
+ "contentEditable,isMap,loop,multiple,noHref,noResize,noShade",
+ "open,readOnly,selected"
+ ].join(",")
+ var boolMap = {}
+ bools.replace(rword, function (name) {
+ boolMap[name.toLowerCase()] = name
+ })
+
+ var propMap = { //属性名映射
+ "accept-charset": "acceptCharset",
+ "char": "ch",
+ "charoff": "chOff",
+ "class": "className",
+ "for": "htmlFor",
+ "http-equiv": "httpEquiv"
+ }
+
+ var anomaly = ["accessKey,bgColor,cellPadding,cellSpacing,codeBase,codeType,colSpan",
+ "dateTime,defaultValue,frameBorder,longDesc,maxLength,marginWidth,marginHeight",
+ "rowSpan,tabIndex,useMap,vSpace,valueType,vAlign"
+ ].join(",")
+ anomaly.replace(rword, function (name) {
+ propMap[name.toLowerCase()] = name
+ })
+
+ var rnoscripts = /<noscript.*?>(?:[\s\S]+?)<\/noscript>/img
+ var rnoscriptText = /<noscript.*?>([\s\S]+?)<\/noscript>/im
+
+ var getXHR = function () {
+ return new (window.XMLHttpRequest || ActiveXObject)("Microsoft.XMLHTTP") // jshint ignore:line
+ }
+
+ var cacheTmpls = avalon.templateCache = {}
+
+ bindingHandlers.attr = function (data, vmodels) {
+ var text = data.value.trim(),
+ simple = true
+ if (text.indexOf(openTag) > -1 && text.indexOf(closeTag) > 2) {
+ simple = false
+ if (rexpr.test(text) && RegExp.rightContext === "" && RegExp.leftContext === "") {
+ simple = true
+ text = RegExp.$1
+ }
+ }
+ if (data.type === "include") {
+ var elem = data.element
+ data.includeRendered = getBindingCallback(elem, "data-include-rendered", vmodels)
+ data.includeLoaded = getBindingCallback(elem, "data-include-loaded", vmodels)
+ var outer = data.includeReplace = !!avalon(elem).data("includeReplace")
+ if (avalon(elem).data("includeCache")) {
+ data.templateCache = {}
+ }
+ data.startInclude = DOC.createComment("ms-include")
+ data.endInclude = DOC.createComment("ms-include-end")
+ if (outer) {
+ data.element = data.startInclude
+ elem.parentNode.insertBefore(data.startInclude, elem)
+ elem.parentNode.insertBefore(data.endInclude, elem.nextSibling)
+ } else {
+ elem.insertBefore(data.startInclude, elem.firstChild)
+ elem.appendChild(data.endInclude)
+ }
+ }
+ data.handlerName = "attr" //handleName用于处理多种绑定共用同一种bindingExecutor的情况
+ parseExprProxy(text, vmodels, data, (simple ? 0 : scanExpr(data.value)))
+ }
+
+ bindingExecutors.attr = function (val, elem, data) {
+ var method = data.type,
+ attrName = data.param
+ if (method === "css") {
+ avalon(elem).css(attrName, val)
+ } else if (method === "attr") {
+ // ms-attr-class="xxx" vm.xxx="aaa bbb ccc"将元素的className设置为aaa bbb ccc
+ // ms-attr-class="xxx" vm.xxx=false 清空元素的所有类名
+ // ms-attr-name="yyy" vm.yyy="ooo" 为元素设置name属性
+ var toRemove = (val === false) || (val === null) || (val === void 0)
+
+ if (!W3C && propMap[attrName]) { //旧式IE下需要进行名字映射
+ attrName = propMap[attrName]
+ }
+ var bool = boolMap[attrName]
+ if (typeof elem[bool] === "boolean") {
+ elem[bool] = !!val //布尔属性必须使用el.xxx = true|false方式设值
+ if (!val) { //如果为false, IE全系列下相当于setAttribute(xxx,''),会影响到样式,需要进一步处理
+ toRemove = true
+ }
+ }
+ if (toRemove) {
+ return elem.removeAttribute(attrName)
+ }
+
+ //SVG只能使用setAttribute(xxx, yyy), VML只能使用elem.xxx = yyy ,HTML的固有属性必须elem.xxx = yyy
+ var isInnate = rsvg.test(elem) ? false : (DOC.namespaces && isVML(elem)) ? true : attrName in elem.cloneNode(false)
+ if (isInnate) {
+ elem[attrName] = val
+ } else {
+ elem.setAttribute(attrName, val)
+ }
+ } else if (method === "include" && val) {
+ var vmodels = data.vmodels
+ var rendered = data.includeRendered
+ var loaded = data.includeLoaded
+ var replace = data.includeReplace
+ var target = replace ? elem.parentNode : elem
+ var scanTemplate = function (text) {
+ if (loaded) {
+ var newText = loaded.apply(target, [text].concat(vmodels))
+ if (typeof newText === "string")
+ text = newText
+ }
+ if (rendered) {
+ checkScan(target, function () {
+ rendered.call(target)
+ }, NaN)
+ }
+ var lastID = data.includeLastID
+ if (data.templateCache && lastID && lastID !== val) {
+ var lastTemplate = data.templateCache[lastID]
+ if (!lastTemplate) {
+ lastTemplate = data.templateCache[lastID] = DOC.createElement("div")
+ ifGroup.appendChild(lastTemplate)
+ }
+ }
+ data.includeLastID = val
+ while (true) {
+ var node = data.startInclude.nextSibling
+ if (node && node !== data.endInclude) {
+ target.removeChild(node)
+ if (lastTemplate)
+ lastTemplate.appendChild(node)
+ } else {
+ break
+ }
+ }
+ var dom = getTemplateNodes(data, val, text)
+ var nodes = avalon.slice(dom.childNodes)
+ target.insertBefore(dom, data.endInclude)
+ scanNodeArray(nodes, vmodels)
+ }
+
+ if (data.param === "src") {
+ if (typeof cacheTmpls[val] === "string") {
+ avalon.nextTick(function () {
+ scanTemplate(cacheTmpls[val])
+ })
+ } else if (Array.isArray(cacheTmpls[val])) { //#805 防止在循环绑定中发出许多相同的请求
+ cacheTmpls[val].push(scanTemplate)
+ } else {
+ var xhr = getXHR()
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ var s = xhr.status
+ if (s >= 200 && s < 300 || s === 304 || s === 1223) {
+ var text = xhr.responseText
+ for (var f = 0, fn; fn = cacheTmpls[val][f++];) {
+ fn(text)
+ }
+ cacheTmpls[val] = text
+ }
+ }
+ }
+ cacheTmpls[val] = [scanTemplate]
+ xhr.open("GET", val, true)
+ if ("withCredentials" in xhr) {
+ xhr.withCredentials = true
+ }
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
+ xhr.send(null)
+ }
+ } else {
+ //IE系列与够新的标准浏览器支持通过ID取得元素(firefox14+)
+ //http://tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/
+ var el = val && val.nodeType === 1 ? val : DOC.getElementById(val)
+ if (el) {
+ if (el.tagName === "NOSCRIPT" && !(el.innerHTML || el.fixIE78)) { //IE7-8 innerText,innerHTML都无法取得其内容,IE6能取得其innerHTML
+ xhr = getXHR() //IE9-11与chrome的innerHTML会得到转义的内容,它们的innerText可以
+ xhr.open("GET", location, false) //谢谢Nodejs 乱炖群 深圳-纯属虚构
+ xhr.send(null)
+ //http://bbs.csdn.net/topics/390349046?page=1#post-393492653
+ var noscripts = DOC.getElementsByTagName("noscript")
+ var array = (xhr.responseText || "").match(rnoscripts) || []
+ var n = array.length
+ for (var i = 0; i < n; i++) {
+ var tag = noscripts[i]
+ if (tag) { //IE6-8中noscript标签的innerHTML,innerText是只读的
+ tag.style.display = "none" //http://haslayout.net/css/noscript-Ghost-Bug
+ tag.fixIE78 = (array[i].match(rnoscriptText) || ["", " "])[1]
+ }
+ }
+ }
+ avalon.nextTick(function () {
+ scanTemplate(el.fixIE78 || el.value || el.innerText || el.innerHTML)
+ })
+ }
+ }
+ } else {
+ if (!root.hasAttribute && typeof val === "string" && (method === "src" || method === "href")) {
+ val = val.replace(/&/g, "&") //处理IE67自动转义的问题
+ }
+ elem[method] = val
+ if (window.chrome && elem.tagName === "EMBED") {
+ var parent = elem.parentNode //#525 chrome1-37下embed标签动态设置src不能发生请求
+ var comment = document.createComment("ms-src")
+ parent.replaceChild(comment, elem)
+ parent.replaceChild(elem, comment)
+ }
+ }
+ }
+
+ function getTemplateNodes(data, id, text) {
+ var div = data.templateCache && data.templateCache[id]
+ if (div) {
+ var dom = DOC.createDocumentFragment(),
+ firstChild
+ while (firstChild = div.firstChild) {
+ dom.appendChild(firstChild)
+ }
+ return dom
+ }
+ return avalon.parseHTML(text)
+ }
+
+//这几个指令都可以使用插值表达式,如ms-src="aaa/{{b}}/{{c}}.html"
+ "title,alt,src,value,css,include,href".replace(rword, function (name) {
+ bindingHandlers[name] = bindingHandlers.attr
+ })
+//根据VM的属性值或表达式的值切换类名,ms-class="xxx yyy zzz:flag"
+//http://www.cnblogs.com/rubylouvre/archive/2012/12/17/2818540.html
+ bindingHandlers["class"] = function (data, vmodels) {
+ var oldStyle = data.param,
+ text = data.value,
+ rightExpr
+ data.handlerName = "class"
+ if (!oldStyle || isFinite(oldStyle)) {
+ data.param = "" //去掉数字
+ var noExpr = text.replace(rexprg, function (a) {
+ return a.replace(/./g, "0")
+ //return Math.pow(10, a.length - 1) //将插值表达式插入10的N-1次方来占位
+ })
+ var colonIndex = noExpr.indexOf(":") //取得第一个冒号的位置
+ if (colonIndex === -1) { // 比如 ms-class="aaa bbb ccc" 的情况
+ var className = text
+ } else { // 比如 ms-class-1="ui-state-active:checked" 的情况
+ className = text.slice(0, colonIndex)
+ rightExpr = text.slice(colonIndex + 1)
+ parseExpr(rightExpr, vmodels, data) //决定是添加还是删除
+ if (!data.evaluator) {
+ log("debug: ms-class '" + (rightExpr || "").trim() + "' 不存在于VM中")
+ return false
+ } else {
+ data._evaluator = data.evaluator
+ data._args = data.args
+ }
+ }
+ var hasExpr = rexpr.test(className) //比如ms-class="width{{w}}"的情况
+ if (!hasExpr) {
+ data.immobileClass = className
+ }
+ parseExprProxy("", vmodels, data, (hasExpr ? scanExpr(className) : 0))
+ } else {
+ data.immobileClass = data.oldStyle = data.param
+ parseExprProxy(text, vmodels, data)
+ }
+ }
+
+ bindingExecutors["class"] = function (val, elem, data) {
+ var $elem = avalon(elem),
+ method = data.type
+ if (method === "class" && data.oldStyle) { //如果是旧风格
+ $elem.toggleClass(data.oldStyle, !!val)
+ } else {
+ //如果存在冒号就有求值函数
+ data.toggleClass = data._evaluator ? !!data._evaluator.apply(elem, data._args) : true
+ data.newClass = data.immobileClass || val
+ if (data.oldClass && data.newClass !== data.oldClass) {
+ $elem.removeClass(data.oldClass)
+ }
+ data.oldClass = data.newClass
+ switch (method) {
+ case "class":
+ $elem.toggleClass(data.newClass, data.toggleClass)
+ break
+ case "hover":
+ case "active":
+ if (!data.hasBindEvent) { //确保只绑定一次
+ var activate = "mouseenter" //在移出移入时切换类名
+ var abandon = "mouseleave"
+ if (method === "active") { //在聚焦失焦中切换类名
+ elem.tabIndex = elem.tabIndex || -1
+ activate = "mousedown"
+ abandon = "mouseup"
+ var fn0 = $elem.bind("mouseleave", function () {
+ data.toggleClass && $elem.removeClass(data.newClass)
+ })
+ }
+ var fn1 = $elem.bind(activate, function () {
+ data.toggleClass && $elem.addClass(data.newClass)
+ })
+ var fn2 = $elem.bind(abandon, function () {
+ data.toggleClass && $elem.removeClass(data.newClass)
+ })
+ data.rollback = function () {
+ $elem.unbind("mouseleave", fn0)
+ $elem.unbind(activate, fn1)
+ $elem.unbind(abandon, fn2)
+ }
+ data.hasBindEvent = true
+ }
+ break;
+ }
+ }
+ }
+
+ "hover,active".replace(rword, function (method) {
+ bindingHandlers[method] = bindingHandlers["class"]
+ })
+//ms-controller绑定已经在scanTag 方法中实现
+//ms-css绑定已由ms-attr绑定实现
+
+
+// bindingHandlers.data 定义在if.js
+ bindingExecutors.data = function (val, elem, data) {
+ var key = "data-" + data.param
+ if (val && typeof val === "object") {
+ elem[key] = val
+ } else {
+ elem.setAttribute(key, String(val))
+ }
+ }
+//双工绑定
+ var duplexBinding = bindingHandlers.duplex = function (data, vmodels) {
+ var elem = data.element,
+ hasCast
+ parseExprProxy(data.value, vmodels, data, 0, 1)
+
+ data.changed = getBindingCallback(elem, "data-duplex-changed", vmodels) || noop
+ if (data.evaluator && data.args) {
+ var params = []
+ var casting = oneObject("string,number,boolean,checked")
+ if (elem.type === "radio" && data.param === "") {
+ data.param = "checked"
+ }
+ if (elem.msData) {
+ elem.msData["ms-duplex"] = data.value
+ }
+ data.param.replace(/\w+/g, function (name) {
+ if (/^(checkbox|radio)$/.test(elem.type) && /^(radio|checked)$/.test(name)) {
+ if (name === "radio")
+ log("ms-duplex-radio已经更名为ms-duplex-checked")
+ name = "checked"
+ data.isChecked = true
+ }
+ if (name === "bool") {
+ name = "boolean"
+ log("ms-duplex-bool已经更名为ms-duplex-boolean")
+ } else if (name === "text") {
+ name = "string"
+ log("ms-duplex-text已经更名为ms-duplex-string")
+ }
+ if (casting[name]) {
+ hasCast = true
+ }
+ avalon.Array.ensure(params, name)
+ })
+ if (!hasCast) {
+ params.push("string")
+ }
+ data.param = params.join("-")
+ data.bound = function (type, callback) {
+ if (elem.addEventListener) {
+ elem.addEventListener(type, callback, false)
+ } else {
+ elem.attachEvent("on" + type, callback)
+ }
+ var old = data.rollback
+ data.rollback = function () {
+ elem.avalonSetter = null
+ avalon.unbind(elem, type, callback)
+ old && old()
+ }
+ }
+ for (var i in avalon.vmodels) {
+ var v = avalon.vmodels[i]
+ v.$fire("avalon-ms-duplex-init", data)
+ }
+ var cpipe = data.pipe || (data.pipe = pipe)
+ cpipe(null, data, "init")
+ var tagName = elem.tagName
+ duplexBinding[tagName] && duplexBinding[tagName](elem, data.evaluator.apply(null, data.args), data)
+ }
+ }
+//不存在 bindingExecutors.duplex
+
+ function fixNull(val) {
+ return val == null ? "" : val
+ }
+
+ avalon.duplexHooks = {
+ checked: {
+ get: function (val, data) {
+ return !data.element.oldValue
+ }
+ },
+ string: {
+ get: function (val) { //同步到VM
+ return val
+ },
+ set: fixNull
+ },
+ "boolean": {
+ get: function (val) {
+ return val === "true"
+ },
+ set: fixNull
+ },
+ number: {
+ get: function (val, data) {
+ var number = parseFloat(val)
+ if (-val === -number) {
+ return number
+ }
+ var arr = /strong|medium|weak/.exec(data.element.getAttribute("data-duplex-number")) || ["medium"]
+ switch (arr[0]) {
+ case "strong":
+ return 0
+ case "medium":
+ return val === "" ? "" : 0
+ case "weak":
+ return val
+ }
+ },
+ set: fixNull
+ }
+ }
+
+ function pipe(val, data, action, e) {
+ data.param.replace(/\w+/g, function (name) {
+ var hook = avalon.duplexHooks[name]
+ if (hook && typeof hook[action] === "function") {
+ val = hook[action](val, data)
+ }
+ })
+ return val
+ }
+
+ var TimerID, ribbon = []
+
+ avalon.tick = function (fn) {
+ if (ribbon.push(fn) === 1) {
+ TimerID = setInterval(ticker, 60)
+ }
+ }
+
+ function ticker() {
+ for (var n = ribbon.length - 1; n >= 0; n--) {
+ var el = ribbon[n]
+ if (el() === false) {
+ ribbon.splice(n, 1)
+ }
+ }
+ if (!ribbon.length) {
+ clearInterval(TimerID)
+ }
+ }
+
+ var watchValueInTimer = noop
+ var rmsinput = /text|password|hidden/
+ new function () { // jshint ignore:line
+ try { //#272 IE9-IE11, firefox
+ var setters = {}
+ var aproto = HTMLInputElement.prototype
+ var bproto = HTMLTextAreaElement.prototype
+
+ function newSetter(value) { // jshint ignore:line
+ if (avalon.contains(root, this)) {
+ setters[this.tagName].call(this, value)
+ if (!rmsinput.test(this.type))
+ return
+ if (!this.msFocus && this.avalonSetter) {
+ this.avalonSetter()
+ }
+ }
+ }
+
+ var inputProto = HTMLInputElement.prototype
+ Object.getOwnPropertyNames(inputProto) //故意引发IE6-8等浏览器报错
+ setters["INPUT"] = Object.getOwnPropertyDescriptor(aproto, "value").set
+ Object.defineProperty(aproto, "value", {
+ set: newSetter
+ })
+ setters["TEXTAREA"] = Object.getOwnPropertyDescriptor(bproto, "value").set
+ Object.defineProperty(bproto, "value", {
+ set: newSetter
+ })
+ } catch (e) {
+ //在chrome 43中 ms-duplex终于不需要使用定时器实现双向绑定了
+ // http://updates.html5rocks.com/2015/04/DOM-attributes-now-on-the-prototype
+ // https://docs.google.com/document/d/1jwA8mtClwxI-QJuHT7872Z0pxpZz8PBkf2bGAbsUtqs/edit?pli=1
+ watchValueInTimer = avalon.tick
+ }
+ } // jshint ignore:line
+//处理radio, checkbox, text, textarea, password
+ duplexBinding.INPUT = function (element, evaluator, data) {
+ var $type = element.type,
+ bound = data.bound,
+ $elem = avalon(element),
+ composing = false
+
+ function callback(value) {
+ data.changed.call(this, value, data)
+ }
+
+ function compositionStart() {
+ composing = true
+ }
+
+ function compositionEnd() {
+ composing = false
+ }
+
+ //当value变化时改变model的值
+
+ var updateVModel = function () {
+ if (composing) //处理中文输入法在minlengh下引发的BUG
+ return
+ var val = element.oldValue = element.value //防止递归调用形成死循环
+ var lastValue = data.pipe(val, data, "get")
+ if ($elem.data("duplexObserve") !== false) {
+ evaluator(lastValue)
+ callback.call(element, lastValue)
+ if ($elem.data("duplex-focus")) {
+ avalon.nextTick(function () {
+ element.focus()
+ })
+ }
+ }
+ }
+ //当model变化时,它就会改变value的值
+ data.handler = function () {
+ var val = data.pipe(evaluator(), data, "set") + ""
+ if (val !== element.oldValue) {
+ element.value = val
+ }
+ }
+ if (data.isChecked || $type === "radio") {
+ updateVModel = function () {
+ if ($elem.data("duplexObserve") !== false) {
+ var lastValue = data.pipe(element.value, data, "get")
+ evaluator(lastValue)
+ callback.call(element, lastValue)
+ }
+ }
+ data.handler = function () {
+ var val = evaluator()
+ var checked = data.isChecked ? !!val : val + "" === element.value
+ element.checked = element.oldValue = checked
+ }
+ bound("click", updateVModel)
+ } else if ($type === "checkbox") {
+ updateVModel = function () {
+ if ($elem.data("duplexObserve") !== false) {
+ var method = element.checked ? "ensure" : "remove"
+ var array = evaluator()
+ if (!Array.isArray(array)) {
+ log("ms-duplex应用于checkbox上要对应一个数组")
+ array = [array]
+ }
+ avalon.Array[method](array, data.pipe(element.value, data, "get"))
+ callback.call(element, array)
+ }
+ }
+ data.handler = function () {
+ var array = [].concat(evaluator()) //强制转换为数组
+ element.checked = array.indexOf(data.pipe(element.value, data, "get")) > -1
+ }
+ bound("change", updateVModel)
+ } else {
+ var events = element.getAttribute("data-duplex-event") || "input"
+ if (element.attributes["data-event"]) {
+ log("data-event指令已经废弃,请改用data-duplex-event")
+ }
+ events.replace(rword, function (name) {
+ switch (name) {
+ case "input":
+ bound("input", updateVModel)
+ bound("DOMAutoComplete", updateVModel)
+ if (!IEVersion) {
+ bound("compositionstart", compositionStart)
+ bound("compositionend", compositionEnd)
+ }
+ break
+ default:
+ bound(name, updateVModel)
+ break
+ }
+ })
+ bound("focus", function () {
+ element.msFocus = true
+ })
+ bound("blur", function () {
+ element.msFocus = false
+ })
+ if (rmsinput.test($type)) {
+ watchValueInTimer(function () {
+ if (root.contains(element)) {
+ if (!element.msFocus && element.oldValue !== element.value) {
+ updateVModel()
+ }
+ } else if (!element.msRetain) {
+ return false
+ }
+ })
+ }
+
+ element.avalonSetter = updateVModel
+ }
+
+ element.oldValue = element.value
+ avalon.injectBinding(data)
+ callback.call(element, element.value)
+ }
+ duplexBinding.TEXTAREA = duplexBinding.INPUT
+ duplexBinding.SELECT = function (element, evaluator, data) {
+ var $elem = avalon(element)
+
+ function updateVModel() {
+ if ($elem.data("duplexObserve") !== false) {
+ var val = $elem.val() //字符串或字符串数组
+ if (Array.isArray(val)) {
+ val = val.map(function (v) {
+ return data.pipe(v, data, "get")
+ })
+ } else {
+ val = data.pipe(val, data, "get")
+ }
+ if (val + "" !== element.oldValue) {
+ evaluator(val)
+ }
+ data.changed.call(element, val, data)
+ }
+ }
+
+ data.handler = function () {
+ var val = evaluator()
+ val = val && val.$model || val
+ if (Array.isArray(val)) {
+ if (!element.multiple) {
+ log("ms-duplex在<select multiple=true>上要求对应一个数组")
+ }
+ } else {
+ if (element.multiple) {
+ log("ms-duplex在<select multiple=false>不能对应一个数组")
+ }
+ }
+ //必须变成字符串后才能比较
+ val = Array.isArray(val) ? val.map(String) : val + ""
+ if (val + "" !== element.oldValue) {
+ $elem.val(val)
+ element.oldValue = val + ""
+ }
+ }
+ data.bound("change", updateVModel)
+ element.msCallback = function () {
+ avalon.injectBinding(data)
+ data.changed.call(element, evaluator(), data)
+ }
+ }
+// bindingHandlers.html 定义在if.js
+ bindingExecutors.html = function (val, elem, data) {
+ val = val == null ? "" : val
+ var isHtmlFilter = "group" in data
+ var parent = isHtmlFilter ? elem.parentNode : elem
+ if (!parent)
+ return
+ if (typeof val === "string") {
+ var fragment = avalon.parseHTML(val)
+ } else if (val.nodeType === 11) { //将val转换为文档碎片
+ fragment = val
+ } else if (val.nodeType === 1 || val.item) {
+ var nodes = val.nodeType === 1 ? val.childNodes : val.item
+ fragment = hyperspace.cloneNode(true)
+ while (nodes[0]) {
+ fragment.appendChild(nodes[0])
+ }
+ }
+ if (!fragment.firstChild) {
+ fragment.appendChild(DOC.createComment("ms-html"))
+ }
+ nodes = avalon.slice(fragment.childNodes)
+ //插入占位符, 如果是过滤器,需要有节制地移除指定的数量,如果是html指令,直接清空
+ if (isHtmlFilter) {
+ var n = data.group,
+ i = 1
+
+ data.group = nodes.length
+ data.element = nodes[0]
+
+ while (i < n) {
+ var node = elem.nextSibling
+ if (node) {
+ parent.removeChild(node)
+ i++
+ }
+ }
+ parent.replaceChild(fragment, elem)
+ } else {
+ avalon.clearHTML(parent).appendChild(fragment)
+ }
+ scanNodeArray(nodes, data.vmodels)
+ }
+ bindingHandlers["if"] =
+ bindingHandlers.data =
+ bindingHandlers.text =
+ bindingHandlers.html =
+ function (data, vmodels) {
+ parseExprProxy(data.value, vmodels, data)
+ }
+
+ bindingExecutors["if"] = function (val, elem, data) {
+ if (val) { //插回DOM树
+ if (elem.nodeType === 8) {
+ elem.parentNode.replaceChild(data.template, elem)
+ elem = data.element = data.template //这时可能为null
+ }
+ if (elem.getAttribute(data.name)) {
+ elem.removeAttribute(data.name)
+ scanAttr(elem, data.vmodels)
+ }
+ data.rollback = null
+ } else { //移出DOM树,并用注释节点占据原位置
+ if (elem.nodeType === 1) {
+ var node = data.element = DOC.createComment("ms-if")
+ elem.parentNode.replaceChild(node, elem)
+ data.template = elem //元素节点
+ ifGroup.appendChild(elem)
+ data.rollback = function () {
+ if (elem.parentNode === ifGroup) {
+ ifGroup.removeChild(elem)
+ }
+ }
+ }
+ }
+ }
+//ms-important绑定已经在scanTag 方法中实现
+//ms-include绑定已由ms-attr绑定实现
+
+ var rdash = /\(([^)]*)\)/
+ bindingHandlers.on = function (data, vmodels) {
+ var value = data.value
+ data.type = "on"
+ var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
+ if (typeof bindingHandlers.on[eventType + "Hook"] === "function") {
+ bindingHandlers.on[eventType + "Hook"](data)
+ }
+ if (value.indexOf("(") > 0 && value.indexOf(")") > -1) {
+ var matched = (value.match(rdash) || ["", ""])[1].trim()
+ if (matched === "" || matched === "$event") { // aaa() aaa($event)当成aaa处理
+ value = value.replace(rdash, "")
+ }
+ }
+ parseExprProxy(value, vmodels, data)
+ }
+
+ bindingExecutors.on = function (callback, elem, data) {
+ callback = function (e) {
+ var fn = data.evaluator || noop
+ return fn.apply(this, data.args.concat(e))
+ }
+ var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
+ if (eventType === "scan") {
+ callback.call(elem, {
+ type: eventType
+ })
+ } else if (typeof data.specialBind === "function") {
+ data.specialBind(elem, callback)
+ } else {
+ var removeFn = avalon.bind(elem, eventType, callback)
+ }
+ data.rollback = function () {
+ if (typeof data.specialUnbind === "function") {
+ data.specialUnbind()
+ } else {
+ avalon.unbind(elem, eventType, removeFn)
+ }
+ }
+ }
+ bindingHandlers.repeat = function (data, vmodels) {
+ var type = data.type
+ parseExprProxy(data.value, vmodels, data, 0, 1)
+ var freturn = false
+ try {
+ var $repeat = data.$repeat = data.evaluator.apply(0, data.args || [])
+ var xtype = avalon.type($repeat)
+ if (xtype !== "object" && xtype !== "array") {
+ freturn = true
+ avalon.log("warning:" + data.value + "只能是对象或数组")
+ }
+ } catch (e) {
+ freturn = true
+ }
+
+ var arr = data.value.split(".") || []
+ if (arr.length > 1) {
+ arr.pop()
+ var n = arr[0]
+ for (var i = 0, v; v = vmodels[i++];) {
+ if (v && v.hasOwnProperty(n)) {
+ var events = v[n].$events || {}
+ events[subscribers] = events[subscribers] || []
+ events[subscribers].push(data)
+ break
+ }
+ }
+ }
+ var elem = data.element
+ elem.removeAttribute(data.name)
+
+ data.sortedCallback = getBindingCallback(elem, "data-with-sorted", vmodels)
+ data.renderedCallback = getBindingCallback(elem, "data-" + type + "-rendered", vmodels)
+ var signature = generateID(type)
+ var comment = data.element = DOC.createComment(signature + ":end")
+ data.clone = DOC.createComment(signature)
+ hyperspace.appendChild(comment)
+
+ if (type === "each" || type === "with") {
+ data.template = elem.innerHTML.trim()
+ avalon.clearHTML(elem).appendChild(comment)
+ } else {
+ data.template = elem.outerHTML.trim()
+ elem.parentNode.replaceChild(comment, elem)
+ }
+ data.template = avalon.parseHTML(data.template)
+ data.rollback = function () {
+ var elem = data.element
+ if (!elem)
+ return
+ bindingExecutors.repeat.call(data, "clear")
+ var parentNode = elem.parentNode
+ var content = data.template
+ var target = content.firstChild
+ parentNode.replaceChild(content, elem)
+ var start = data.$with
+ start && start.parentNode && start.parentNode.removeChild(start)
+ target = data.element = data.type === "repeat" ? target : parentNode
+ }
+ if (freturn) {
+ return
+ }
+ data.handler = bindingExecutors.repeat
+ data.$outer = {}
+ var check0 = "$key"
+ var check1 = "$val"
+ if (Array.isArray($repeat)) {
+ $repeat.$map[data.param || "el"] = 1
+ check0 = "$first"
+ check1 = "$last"
+ }
+ for (i = 0; v = vmodels[i++];) {
+ if (v.hasOwnProperty(check0) && v.hasOwnProperty(check1)) {
+ data.$outer = v
+ break
+ }
+ }
+ var $events = $repeat.$events
+ var $list = ($events || {})[subscribers]
+ if ($list && avalon.Array.ensure($list, data)) {
+ addSubscribers(data, $list)
+ }
+ if (xtype === "object") {
+ data.$with = true
+ var pool = !$events ? {} : $events.$withProxyPool || ($events.$withProxyPool = {})
+ data.handler("append", $repeat, pool)
+ } else if ($repeat.length) {
+ data.handler("add", 0, $repeat.length)
+ }
+ }
+
+ bindingExecutors.repeat = function (method, pos, el) {
+ if (method) {
+ var data = this, start, fragment
+ var end = data.element
+ var comments = getComments(data)
+ var parent = end.parentNode
+ var transation = hyperspace.cloneNode(false)
+ switch (method) {
+ case "add": //在pos位置后添加el数组(pos为插入位置,el为要插入的个数)
+ var n = pos + el
+ var fragments = []
+ var array = data.$repeat
+ for (var i = pos; i < n; i++) {
+ var proxy = array.$proxy[i]
+ proxy.$outer = data.$outer
+ shimController(data, transation, proxy, fragments)
+ }
+ parent.insertBefore(transation, comments[pos] || end)
+ for (i = 0; fragment = fragments[i++];) {
+ scanNodeArray(fragment.nodes, fragment.vmodels)
+ fragment.nodes = fragment.vmodels = null
+ }
+ break
+ case "del": //将pos后的el个元素删掉(pos, el都是数字)
+ sweepNodes(comments[pos], comments[pos + el] || end)
+ break
+ case "clear":
+ start = comments[0]
+ if (start) {
+ sweepNodes(start, end)
+ }
+ break
+ case "move":
+ start = comments[0]
+ if (start) {
+ var signature = start.nodeValue
+ var rooms = []
+ var room = [],
+ node
+ sweepNodes(start, end, function () {
+ room.unshift(this)
+ if (this.nodeValue === signature) {
+ rooms.unshift(room)
+ room = []
+ }
+ })
+ sortByIndex(rooms, pos)
+ while (room = rooms.shift()) {
+ while (node = room.shift()) {
+ transation.appendChild(node)
+ }
+ }
+ parent.insertBefore(transation, end)
+ }
+ break
+ case "append": //将pos的键值对从el中取出(pos为一个普通对象,el为预先生成好的代理VM对象池)
+ var pool = el
+ var keys = []
+ fragments = []
+ for (var key in pos) { //得到所有键名
+ if (pos.hasOwnProperty(key) && key !== "hasOwnProperty") {
+ keys.push(key)
+ }
+ }
+ if (data.sortedCallback) { //如果有回调,则让它们排序
+ var keys2 = data.sortedCallback.call(parent, keys)
+ if (keys2 && Array.isArray(keys2) && keys2.length) {
+ keys = keys2
+ }
+ }
+ for (i = 0; key = keys[i++];) {
+ if (key !== "hasOwnProperty") {
+ if (!pool[key]) {
+ pool[key] = withProxyAgent(key, data)
+ }
+ shimController(data, transation, pool[key], fragments)
+ }
+ }
+ var comment = data.$with = data.clone
+ parent.insertBefore(comment, end)
+ parent.insertBefore(transation, end)
+ for (i = 0; fragment = fragments[i++];) {
+ scanNodeArray(fragment.nodes, fragment.vmodels)
+ fragment.nodes = fragment.vmodels = null
+ }
+ break
+ }
+ if (method === "clear")
+ method = "del"
+ var callback = data.renderedCallback || noop,
+ args = arguments
+ checkScan(parent, function () {
+ callback.apply(parent, args)
+ if (parent.oldValue && parent.tagName === "SELECT") { //fix #503
+ avalon(parent).val(parent.oldValue.split(","))
+ }
+ }, NaN)
+ }
+ }
+
+ "with,each".replace(rword, function (name) {
+ bindingHandlers[name] = bindingHandlers.repeat
+ })
+
+ function shimController(data, transation, proxy, fragments) {
+ var content = data.template.cloneNode(true)
+ var nodes = avalon.slice(content.childNodes)
+ if (!data.$with) {
+ content.insertBefore(data.clone.cloneNode(false), content.firstChild)
+ }
+ transation.appendChild(content)
+ var nv = [proxy].concat(data.vmodels)
+ var fragment = {
+ nodes: nodes,
+ vmodels: nv
+ }
+ fragments.push(fragment)
+ }
+
+ function getComments(data) {
+ var end = data.element
+ var signature = end.nodeValue.replace(":end", "")
+ var node = end.previousSibling
+ var array = []
+ while (node) {
+ if (node.nodeValue === signature) {
+ array.unshift(node)
+ }
+ node = node.previousSibling
+ }
+ return array
+ }
+
+
+//移除掉start与end之间的节点(保留end)
+ function sweepNodes(start, end, callback) {
+ while (true) {
+ var node = end.previousSibling
+ if (!node)
+ break
+ node.parentNode.removeChild(node)
+ callback && callback.call(node)
+ if (node === start) {
+ break
+ }
+ }
+ }
+
+// 为ms-each,ms-with, ms-repeat会创建一个代理VM,
+// 通过它们保持一个下上文,让用户能调用$index,$first,$last,$remove,$key,$val,$outer等属性与方法
+// 所有代理VM的产生,消费,收集,存放通过xxxProxyFactory,xxxProxyAgent, recycleProxies,xxxProxyPool实现
+ var eachProxyPool = []
+ var withProxyPool = []
+
+ function eachProxyFactory() {
+ var source = {
+ $index: 0,
+ $first: false,
+ $last: false,
+ $map: {},
+ $host: [],
+ $outer: {},
+ $remove: avalon.noop,
+ el: {
+ get: function () {
+ var e = this.$events
+ var array = e.$index
+ e.$index = e.el //#817 通过$index为el收集依赖
+ try {
+ return this.$host[this.$index]
+ } finally {
+ e.$index = array
+ }
+ },
+ set: function (val) {
+ this.$host.set(this.$index, val)
+ }
+ }
+ }
+
+ var second = {
+ $last: 1,
+ $first: 1,
+ $index: 1
+ }
+ var proxy = modelFactory(source, second)
+ proxy.$id = generateID("$proxy$each")
+ return proxy
+ }
+
+ function eachProxyAgent(index, host) {
+ var proxy = eachProxyPool.shift()
+ if (!proxy) {
+ proxy = eachProxyFactory()
+ }
+ var last = host.length - 1
+ proxy.$index = index
+ proxy.$first = index === 0
+ proxy.$last = index === last
+ proxy.$map = host.$map
+ proxy.$host = host
+ proxy.$remove = function () {
+ return host.removeAt(proxy.$index)
+ }
+ return proxy
+ }
+
+ function withProxyFactory() {
+ var proxy = modelFactory({
+ $key: "",
+ $outer: {},
+ $host: {},
+ $val: {
+ get: function () {
+ return this.$host[this.$key]
+ },
+ set: function (val) {
+ this.$host[this.$key] = val
+ }
+ }
+ }, {
+ $val: 1
+ })
+ proxy.$id = generateID("$proxy$with")
+ return proxy
+ }
+
+ function withProxyAgent(key, data) {
+ var proxy = withProxyPool.pop()
+ if (!proxy) {
+ proxy = withProxyFactory()
+ }
+ var host = data.$repeat
+ proxy.$key = key
+ proxy.$host = host
+ proxy.$outer = data.$outer
+ if (host.$events) {
+ proxy.$events.$val = host.$events[key]
+ } else {
+ proxy.$events = {}
+ }
+ return proxy
+ }
+
+ function recycleProxies(proxies, type) {
+ var proxyPool = type === "each" ? eachProxyPool : withProxyPool
+ avalon.each(proxies, function (key, proxy) {
+ if (proxy.$events) {
+ for (var i in proxy.$events) {
+ if (Array.isArray(proxy.$events[i])) {
+ proxy.$events[i].forEach(function (data) {
+ if (typeof data === "object")
+ disposeData(data)
+ }) // jshint ignore:line
+ proxy.$events[i].length = 0
+ }
+ }
+ proxy.$host = proxy.$outer = {}
+ if (proxyPool.unshift(proxy) > kernel.maxRepeatSize) {
+ proxyPool.pop()
+ }
+ }
+ })
+ if (type === "each")
+ proxies.length = 0
+ }
+
+ /*********************************************************************
+ * 各种指令 *
+ **********************************************************************/
+//ms-skip绑定已经在scanTag 方法中实现
+// bindingHandlers.text 定义在if.js
+ bindingExecutors.text = function (val, elem) {
+ val = val == null ? "" : val //不在页面上显示undefined null
+ if (elem.nodeType === 3) { //绑定在文本节点上
+ try { //IE对游离于DOM树外的节点赋值会报错
+ elem.data = val
+ } catch (e) {
+ }
+ } else { //绑定在特性节点上
+ elem.textContent = val
+ }
+ }
+ function parseDisplay(nodeName, val) {
+ //用于取得此类标签的默认display值
+ var key = "_" + nodeName
+ if (!parseDisplay[key]) {
+ var node = DOC.createElement(nodeName)
+ root.appendChild(node)
+ if (W3C) {
+ val = getComputedStyle(node, null).display
+ } else {
+ val = node.currentStyle.display
+ }
+ root.removeChild(node)
+ parseDisplay[key] = val
+ }
+ return parseDisplay[key]
+ }
+
+ avalon.parseDisplay = parseDisplay
+
+ bindingHandlers.visible = function (data, vmodels) {
+ var elem = avalon(data.element)
+ var display = elem.css("display")
+ if (display === "none") {
+ var style = elem[0].style
+ var has = /visibility/i.test(style.cssText)
+ var visible = elem.css("visibility")
+ style.display = ""
+ style.visibility = "hidden"
+ display = elem.css("display")
+ if (display === "none") {
+ display = parseDisplay(elem[0].nodeName)
+ }
+ style.visibility = has ? visible : ""
+ }
+ data.display = display
+ parseExprProxy(data.value, vmodels, data)
+ }
+
+ bindingExecutors.visible = function (val, elem, data) {
+ elem.style.display = val ? data.display : "none"
+ }
+ bindingHandlers.widget = function (data, vmodels) {
+ var args = data.value.match(rword)
+ var elem = data.element
+ var widget = args[0]
+ var id = args[1]
+ if (!id || id === "$") { //没有定义或为$时,取组件名+随机数
+ id = generateID(widget)
+ }
+ var optName = args[2] || widget //没有定义,取组件名
+ var constructor = avalon.ui[widget]
+ if (typeof constructor === "function") { //ms-widget="tabs,tabsAAA,optname"
+ vmodels = elem.vmodels || vmodels
+ for (var i = 0, v; v = vmodels[i++];) {
+ if (v.hasOwnProperty(optName) && typeof v[optName] === "object") {
+ var vmOptions = v[optName]
+ vmOptions = vmOptions.$model || vmOptions
+ break
+ }
+ }
+ if (vmOptions) {
+ var wid = vmOptions[widget + "Id"]
+ if (typeof wid === "string") {
+ log("warning!不再支持" + widget + "Id")
+ id = wid
+ }
+ }
+ //抽取data-tooltip-text、data-tooltip-attr属性,组成一个配置对象
+ var widgetData = avalon.getWidgetData(elem, widget)
+ data.value = [widget, id, optName].join(",")
+ data[widget + "Id"] = id
+ data.evaluator = noop
+ elem.msData["ms-widget-id"] = id
+ var options = data[widget + "Options"] = avalon.mix({}, constructor.defaults, vmOptions || {}, widgetData)
+ elem.removeAttribute("ms-widget")
+ var vmodel = constructor(elem, data, vmodels) || {} //防止组件不返回VM
+ if (vmodel.$id) {
+ avalon.vmodels[id] = vmodel
+ createSignalTower(elem, vmodel)
+ try {
+ vmodel.$init(function () {
+ avalon.scan(elem, [vmodel].concat(vmodels))
+ if (typeof options.onInit === "function") {
+ options.onInit.call(elem, vmodel, options, vmodels)
+ }
+ })
+ } catch (e) {
+ }
+ data.rollback = function () {
+ try {
+ vmodel.widgetElement = null
+ vmodel.$remove()
+ } catch (e) {
+ }
+ elem.msData = {}
+ delete avalon.vmodels[vmodel.$id]
+ }
+ addSubscribers(data, widgetList)
+ if (window.chrome) {
+ elem.addEventListener("DOMNodeRemovedFromDocument", function () {
+ setTimeout(removeSubscribers)
+ })
+ }
+ } else {
+ avalon.scan(elem, vmodels)
+ }
+ } else if (vmodels.length) { //如果该组件还没有加载,那么保存当前的vmodels
+ elem.vmodels = vmodels
+ }
+ }
+ var widgetList = []
+//不存在 bindingExecutors.widget
+ /*********************************************************************
+ * 自带过滤器 *
+ **********************************************************************/
+ var rscripts = /<script[^>]*>([\S\s]*?)<\/script\s*>/gim
+ var ron = /\s+(on[^=\s]+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g
+ var ropen = /<\w+\b(?:(["'])[^"]*?(\1)|[^>])*>/ig
+ var rsanitize = {
+ a: /\b(href)\=("javascript[^"]*"|'javascript[^']*')/ig,
+ img: /\b(src)\=("javascript[^"]*"|'javascript[^']*')/ig,
+ form: /\b(action)\=("javascript[^"]*"|'javascript[^']*')/ig
+ }
+ var rsurrogate = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
+ var rnoalphanumeric = /([^\#-~| |!])/g;
+
+ function numberFormat(number, decimals, point, thousands) {
+ //form http://phpjs.org/functions/number_format/
+ //number 必需,要格式化的数字
+ //decimals 可选,规定多少个小数位。
+ //point 可选,规定用作小数点的字符串(默认为 . )。
+ //thousands 可选,规定用作千位分隔符的字符串(默认为 , ),如果设置了该参数,那么所有其他参数都是必需的。
+ number = (number + '')
+ .replace(/[^0-9+\-Ee.]/g, '')
+ var n = !isFinite(+number) ? 0 : +number,
+ prec = !isFinite(+decimals) ? 3 : Math.abs(decimals),
+ sep = thousands || ",",
+ dec = point || ".",
+ s = '',
+ toFixedFix = function (n, prec) {
+ var k = Math.pow(10, prec)
+ return '' + (Math.round(n * k) / k)
+ .toFixed(prec)
+ }
+ // Fix for IE parseFloat(0.55).toFixed(0) = 0;
+ s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
+ .split('.')
+ if (s[0].length > 3) {
+ s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
+ }
+ if ((s[1] || '')
+ .length < prec) {
+ s[1] = s[1] || ''
+ s[1] += new Array(prec - s[1].length + 1)
+ .join('0')
+ }
+ return s.join(dec)
+ }
+
+
+ var filters = avalon.filters = {
+ uppercase: function (str) {
+ return str.toUpperCase()
+ },
+ lowercase: function (str) {
+ return str.toLowerCase()
+ },
+ truncate: function (str, length, truncation) {
+ //length,新字符串长度,truncation,新字符串的结尾的字段,返回新字符串
+ length = length || 30
+ truncation = truncation === void(0) ? "..." : truncation
+ return str.length > length ? str.slice(0, length - truncation.length) + truncation : String(str)
+ },
+ $filter: function (val) {
+ for (var i = 1, n = arguments.length; i < n; i++) {
+ var array = arguments[i]
+ var fn = avalon.filters[array.shift()]
+ if (typeof fn === "function") {
+ var arr = [val].concat(array)
+ val = fn.apply(null, arr)
+ }
+ }
+ return val
+ },
+ camelize: camelize,
+ //https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
+ // <a href="javasc
ript:alert('XSS')">chrome</a>
+ // <a href="data:text/html;base64, PGltZyBzcmM9eCBvbmVycm9yPWFsZXJ0KDEpPg==">chrome</a>
+ // <a href="jav ascript:alert('XSS');">IE67chrome</a>
+ // <a href="jav	ascript:alert('XSS');">IE67chrome</a>
+ // <a href="jav
ascript:alert('XSS');">IE67chrome</a>
+ sanitize: function (str) {
+ return str.replace(rscripts, "").replace(ropen, function (a, b) {
+ var match = a.toLowerCase().match(/<(\w+)\s/)
+ if (match) { //处理a标签的href属性,img标签的src属性,form标签的action属性
+ var reg = rsanitize[match[1]]
+ if (reg) {
+ a = a.replace(reg, function (s, name, value) {
+ var quote = value.charAt(0)
+ return name + "=" + quote + "javascript:void(0)" + quote// jshint ignore:line
+ })
+ }
+ }
+ return a.replace(ron, " ").replace(/\s+/g, " ") //移除onXXX事件
+ })
+ },
+ escape: function (str) {
+ //将字符串经过 str 转义得到适合在页面中显示的内容, 例如替换 < 为 <
+ return String(str).
+ replace(/&/g, '&').
+ replace(rsurrogate, function (value) {
+ var hi = value.charCodeAt(0)
+ var low = value.charCodeAt(1)
+ return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'
+ }).
+ replace(rnoalphanumeric, function (value) {
+ return '&#' + value.charCodeAt(0) + ';'
+ }).
+ replace(/</g, '<').
+ replace(/>/g, '>')
+ },
+ currency: function (amount, symbol, fractionSize) {
+ return (symbol || "\uFFE5") + numberFormat(amount, isFinite(fractionSize) ? fractionSize : 2)
+ },
+ number: numberFormat
+ }
+ /*
+ 'yyyy': 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
+ 'yy': 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
+ 'y': 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
+ 'MMMM': Month in year (January-December)
+ 'MMM': Month in year (Jan-Dec)
+ 'MM': Month in year, padded (01-12)
+ 'M': Month in year (1-12)
+ 'dd': Day in month, padded (01-31)
+ 'd': Day in month (1-31)
+ 'EEEE': Day in Week,(Sunday-Saturday)
+ 'EEE': Day in Week, (Sun-Sat)
+ 'HH': Hour in day, padded (00-23)
+ 'H': Hour in day (0-23)
+ 'hh': Hour in am/pm, padded (01-12)
+ 'h': Hour in am/pm, (1-12)
+ 'mm': Minute in hour, padded (00-59)
+ 'm': Minute in hour (0-59)
+ 'ss': Second in minute, padded (00-59)
+ 's': Second in minute (0-59)
+ 'a': am/pm marker
+ 'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200)
+ format string can also be one of the following predefined localizable formats:
+
+ 'medium': equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 pm)
+ 'short': equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 pm)
+ 'fullDate': equivalent to 'EEEE, MMMM d,y' for en_US locale (e.g. Friday, September 3, 2010)
+ 'longDate': equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010
+ 'mediumDate': equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)
+ 'shortDate': equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10)
+ 'mediumTime': equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 pm)
+ 'shortTime': equivalent to 'h:mm a' for en_US locale (e.g. 12:05 pm)
+ */
+ new function () {// jshint ignore:line
+ function toInt(str) {
+ return parseInt(str, 10) || 0
+ }
+
+ function padNumber(num, digits, trim) {
+ var neg = ""
+ if (num < 0) {
+ neg = '-'
+ num = -num
+ }
+ num = "" + num
+ while (num.length < digits)
+ num = "0" + num
+ if (trim)
+ num = num.substr(num.length - digits)
+ return neg + num
+ }
+
+ function dateGetter(name, size, offset, trim) {
+ return function (date) {
+ var value = date["get" + name]()
+ if (offset > 0 || value > -offset)
+ value += offset
+ if (value === 0 && offset === -12) {
+ value = 12
+ }
+ return padNumber(value, size, trim)
+ }
+ }
+
+ function dateStrGetter(name, shortForm) {
+ return function (date, formats) {
+ var value = date["get" + name]()
+ var get = (shortForm ? ("SHORT" + name) : name).toUpperCase()
+ return formats[get][value]
+ }
+ }
+
+ function timeZoneGetter(date) {
+ var zone = -1 * date.getTimezoneOffset()
+ var paddedZone = (zone >= 0) ? "+" : ""
+ paddedZone += padNumber(Math[zone > 0 ? "floor" : "ceil"](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2)
+ return paddedZone
+ }
+
+ //取得上午下午
+
+ function ampmGetter(date, formats) {
+ return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]
+ }
+
+ var DATE_FORMATS = {
+ yyyy: dateGetter("FullYear", 4),
+ yy: dateGetter("FullYear", 2, 0, true),
+ y: dateGetter("FullYear", 1),
+ MMMM: dateStrGetter("Month"),
+ MMM: dateStrGetter("Month", true),
+ MM: dateGetter("Month", 2, 1),
+ M: dateGetter("Month", 1, 1),
+ dd: dateGetter("Date", 2),
+ d: dateGetter("Date", 1),
+ HH: dateGetter("Hours", 2),
+ H: dateGetter("Hours", 1),
+ hh: dateGetter("Hours", 2, -12),
+ h: dateGetter("Hours", 1, -12),
+ mm: dateGetter("Minutes", 2),
+ m: dateGetter("Minutes", 1),
+ ss: dateGetter("Seconds", 2),
+ s: dateGetter("Seconds", 1),
+ sss: dateGetter("Milliseconds", 3),
+ EEEE: dateStrGetter("Day"),
+ EEE: dateStrGetter("Day", true),
+ a: ampmGetter,
+ Z: timeZoneGetter
+ }
+ var rdateFormat = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/
+ var raspnetjson = /^\/Date\((\d+)\)\/$/
+ filters.date = function (date, format) {
+ var locate = filters.date.locate,
+ text = "",
+ parts = [],
+ fn, match
+ format = format || "mediumDate"
+ format = locate[format] || format
+ if (typeof date === "string") {
+ if (/^\d+$/.test(date)) {
+ date = toInt(date)
+ } else if (raspnetjson.test(date)) {
+ date = +RegExp.$1
+ } else {
+ var trimDate = date.trim()
+ var dateArray = [0, 0, 0, 0, 0, 0, 0]
+ var oDate = new Date(0)
+ //取得年月日
+ trimDate = trimDate.replace(/^(\d+)\D(\d+)\D(\d+)/, function (_, a, b, c) {
+ var array = c.length === 4 ? [c, a, b] : [a, b, c]
+ dateArray[0] = toInt(array[0]) //年
+ dateArray[1] = toInt(array[1]) - 1 //月
+ dateArray[2] = toInt(array[2]) //日
+ return ""
+ })
+ var dateSetter = oDate.setFullYear
+ var timeSetter = oDate.setHours
+ trimDate = trimDate.replace(/[T\s](\d+):(\d+):?(\d+)?\.?(\d)?/, function (_, a, b, c, d) {
+ dateArray[3] = toInt(a) //小时
+ dateArray[4] = toInt(b) //分钟
+ dateArray[5] = toInt(c) //秒
+ if (d) { //毫秒
+ dateArray[6] = Math.round(parseFloat("0." + d) * 1000)
+ }
+ return ""
+ })
+ var tzHour = 0
+ var tzMin = 0
+ trimDate = trimDate.replace(/Z|([+-])(\d\d):?(\d\d)/, function (z, symbol, c, d) {
+ dateSetter = oDate.setUTCFullYear
+ timeSetter = oDate.setUTCHours
+ if (symbol) {
+ tzHour = toInt(symbol + c)
+ tzMin = toInt(symbol + d)
+ }
+ return ""
+ })
+
+ dateArray[3] -= tzHour
+ dateArray[4] -= tzMin
+ dateSetter.apply(oDate, dateArray.slice(0, 3))
+ timeSetter.apply(oDate, dateArray.slice(3))
+ date = oDate
+ }
+ }
+ if (typeof date === "number") {
+ date = new Date(date)
+ }
+ if (avalon.type(date) !== "date") {
+ return
+ }
+ while (format) {
+ match = rdateFormat.exec(format)
+ if (match) {
+ parts = parts.concat(match.slice(1))
+ format = parts.pop()
+ } else {
+ parts.push(format)
+ format = null
+ }
+ }
+ parts.forEach(function (value) {
+ fn = DATE_FORMATS[value]
+ text += fn ? fn(date, locate) : value.replace(/(^'|'$)/g, "").replace(/''/g, "'")
+ })
+ return text
+ }
+ var locate = {
+ AMPMS: {
+ 0: "上午",
+ 1: "下午"
+ },
+ DAY: {
+ 0: "星期日",
+ 1: "星期一",
+ 2: "星期二",
+ 3: "星期三",
+ 4: "星期四",
+ 5: "星期五",
+ 6: "星期六"
+ },
+ MONTH: {
+ 0: "1月",
+ 1: "2月",
+ 2: "3月",
+ 3: "4月",
+ 4: "5月",
+ 5: "6月",
+ 6: "7月",
+ 7: "8月",
+ 8: "9月",
+ 9: "10月",
+ 10: "11月",
+ 11: "12月"
+ },
+ SHORTDAY: {
+ "0": "周日",
+ "1": "周一",
+ "2": "周二",
+ "3": "周三",
+ "4": "周四",
+ "5": "周五",
+ "6": "周六"
+ },
+ fullDate: "y年M月d日EEEE",
+ longDate: "y年M月d日",
+ medium: "yyyy-M-d H:mm:ss",
+ mediumDate: "yyyy-M-d",
+ mediumTime: "H:mm:ss",
+ "short": "yy-M-d ah:mm",
+ shortDate: "yy-M-d",
+ shortTime: "ah:mm"
+ }
+ locate.SHORTMONTH = locate.MONTH
+ filters.date.locate = locate
+ }// jshint ignore:line
+ /*********************************************************************
+ * AMD加载器 *
+ **********************************************************************/
+//https://www.devbridge.com/articles/understanding-amd-requirejs/
+//http://maxogden.com/nested-dependencies.html
+ var modules = avalon.modules = {
+ "domReady!": {
+ exports: avalon,
+ state: 3
+ },
+ "avalon": {
+ exports: avalon,
+ state: 4
+ }
+ }
+//Object(modules[id]).state拥有如下值
+// undefined 没有定义
+// 1(send) 已经发出请求
+// 2(loading) 已经被执行但还没有执行完成,在这个阶段define方法会被执行
+// 3(loaded) 执行完毕,通过onload/onreadystatechange回调判定,在这个阶段checkDeps方法会执行
+// 4(execute) 其依赖也执行完毕, 值放到exports对象上,在这个阶段fireFactory方法会执行
+ modules.exports = modules.avalon
+
+ new function () {// jshint ignore:line
+ var loadings = [] //正在加载中的模块列表
+ var factorys = [] //放置define方法的factory函数
+ var rjsext = /\.js$/i
+
+ function makeRequest(name, config) {
+//1. 去掉资源前缀
+ var res = "js"
+ name = name.replace(/^(\w+)\!/, function (a, b) {
+ res = b
+ return ""
+ })
+ if (res === "ready") {
+ log("debug: ready!已经被废弃,请使用domReady!")
+ res = "domReady"
+ }
+//2. 去掉querystring, hash
+ var query = ""
+ name = name.replace(rquery, function (a) {
+ query = a
+ return ""
+ })
+ //3. 去掉扩展名
+ var suffix = "." + res
+ var ext = /js|css/.test(suffix) ? suffix : ""
+ name = name.replace(/\.[a-z0-9]+$/g, function (a) {
+ if (a === suffix) {
+ ext = a
+ return ""
+ } else {
+ return a
+ }
+ })
+ var req = avalon.mix({
+ query: query,
+ ext: ext,
+ res: res,
+ name: name,
+ toUrl: toUrl
+ }, config)
+ req.toUrl(name)
+ return req
+ }
+
+ function fireRequest(req) {
+ var name = req.name
+ var res = req.res
+ //1. 如果该模块已经发出请求,直接返回
+ var module = modules[name]
+ var urlNoQuery = name && req.urlNoQuery
+ if (module && module.state >= 1) {
+ return name
+ }
+ module = modules[urlNoQuery]
+ if (module && module.state >= 3) {
+ innerRequire(module.deps || [], module.factory, urlNoQuery)
+ return urlNoQuery
+ }
+ if (name && !module) {
+ module = modules[urlNoQuery] = {
+ id: urlNoQuery,
+ state: 1 //send
+ }
+ var wrap = function (obj) {
+ resources[res] = obj
+ obj.load(name, req, function (a) {
+ if (arguments.length && a !== void 0) {
+ module.exports = a
+ }
+ module.state = 4
+ checkDeps()
+ })
+ }
+
+ if (!resources[res]) {
+ innerRequire([res], wrap)
+ } else {
+ wrap(resources[res])
+ }
+ }
+ return name ? urlNoQuery : res + "!"
+ }
+
+//核心API之一 require
+ var requireQueue = []
+ var isUserFirstRequire = false
+ innerRequire = avalon.require = function (array, factory, parentUrl, defineConfig) {
+ if (!isUserFirstRequire) {
+ requireQueue.push(avalon.slice(arguments))
+ if (arguments.length <= 2) {
+ isUserFirstRequire = true
+ var queue = requireQueue.splice(0, requireQueue.length), args
+ while (args = queue.shift()) {
+ innerRequire.apply(null, args)
+ }
+ }
+ return
+ }
+
+ if (!Array.isArray(array)) {
+ avalon.error("require方法的第一个参数应为数组 " + array)
+ }
+ var deps = [] // 放置所有依赖项的完整路径
+ var uniq = createMap()
+ var id = parentUrl || "callback" + setTimeout("1")// jshint ignore:line
+ defineConfig = defineConfig || createMap()
+ defineConfig.baseUrl = kernel.baseUrl
+ var isBuilt = !!defineConfig.built
+ if (parentUrl) {
+ defineConfig.parentUrl = parentUrl.substr(0, parentUrl.lastIndexOf("/"))
+ defineConfig.mapUrl = parentUrl.replace(rjsext, "")
+ }
+ if (isBuilt) {
+ var req = makeRequest(defineConfig.defineName, defineConfig)
+ id = req.urlNoQuery
+ } else {
+ array.forEach(function (name) {
+ var req = makeRequest(name, defineConfig)
+ var url = fireRequest(req) //加载资源,并返回该资源的完整地址
+ if (url) {
+ if (!uniq[url]) {
+ deps.push(url)
+ uniq[url] = "司徒正美" //去重
+ }
+ }
+ })
+ }
+
+ var module = modules[id]
+ if (!module || module.state !== 4) {
+ modules[id] = {
+ id: id,
+ deps: isBuilt ? array.concat() : deps,
+ factory: factory || noop,
+ state: 3
+ }
+ }
+ if (!module) {
+ //如果此模块是定义在另一个JS文件中, 那必须等该文件加载完毕, 才能放到检测列队中
+ loadings.push(id)
+ }
+ checkDeps()
+ }
+
+//核心API之二 require
+ innerRequire.define = function (name, deps, factory) { //模块名,依赖列表,模块本身
+ if (typeof name !== "string") {
+ factory = deps
+ deps = name
+ name = "anonymous"
+ }
+ if (!Array.isArray(deps)) {
+ factory = deps
+ deps = []
+ }
+ var config = {
+ built: !isUserFirstRequire, //用r.js打包后,所有define会放到requirejs之前
+ defineName: name
+ }
+ var args = [deps, factory, config]
+ factory.require = function (url) {
+ args.splice(2, 0, url)
+ if (modules[url]) {
+ modules[url].state = 3 //loaded
+ var isCycle = false
+ try {
+ isCycle = checkCycle(modules[url].deps, url)
+ } catch (e) {
+ }
+ if (isCycle) {
+ avalon.error(url + "模块与之前的模块存在循环依赖,请不要直接用script标签引入" + url + "模块")
+ }
+ }
+ delete factory.require //释放内存
+ innerRequire.apply(null, args) //0,1,2 --> 1,2,0
+ }
+//根据标准,所有遵循W3C标准的浏览器,script标签会按标签的出现顺序执行。
+//老的浏览器中,加载也是按顺序的:一个文件下载完成后,才开始下载下一个文件。
+//较新的浏览器中(IE8+ 、FireFox3.5+ 、Chrome4+ 、Safari4+),为了减小请求时间以优化体验,
+//下载可以是并行的,但是执行顺序还是按照标签出现的顺序。
+//但如果script标签是动态插入的, 就未必按照先请求先执行的原则了,目测只有firefox遵守
+//唯一比较一致的是,IE10+及其他标准浏览器,一旦开始解析脚本, 就会一直堵在那里,直接脚本解析完毕
+//亦即,先进入loading阶段的script标签(模块)必然会先进入loaded阶段
+ var url = config.built ? "unknown" : getCurrentScript()
+ if (url) {
+ var module = modules[url]
+ if (module) {
+ module.state = 2
+ }
+ factory.require(url)
+ } else {//合并前后的safari,合并后的IE6-9走此分支
+ factorys.push(factory)
+ }
+ }
+//核心API之三 require.config(settings)
+ innerRequire.config = kernel
+ //核心API之四 define.amd 标识其符合AMD规范
+ innerRequire.define.amd = modules
+
+ //==========================对用户配置项进行再加工==========================
+ var allpaths = kernel["orig.paths"] = createMap()
+ var allmaps = kernel["orig.map"] = createMap()
+ var allpackages = kernel["packages"] = []
+ var allargs = kernel["orig.args"] = createMap()
+ avalon.mix(plugins, {
+ paths: function (hash) {
+ avalon.mix(allpaths, hash)
+ kernel.paths = makeIndexArray(allpaths)
+ },
+ map: function (hash) {
+ avalon.mix(allmaps, hash)
+ var list = makeIndexArray(allmaps, 1, 1)
+ avalon.each(list, function (_, item) {
+ item.val = makeIndexArray(item.val)
+ })
+ kernel.map = list
+ },
+ packages: function (array) {
+ array = array.concat(allpackages)
+ var uniq = createMap()
+ var ret = []
+ for (var i = 0, pkg; pkg = array[i++];) {
+ pkg = typeof pkg === "string" ? {name: pkg} : pkg
+ var name = pkg.name
+ if (!uniq[name]) {
+ var url = joinPath(pkg.location || name, pkg.main || "main")
+ url = url.replace(rjsext, "")
+ ret.push(pkg)
+ uniq[name] = pkg.location = url
+ pkg.reg = makeMatcher(name)
+ }
+ }
+ kernel.packages = ret.sort()
+ },
+ urlArgs: function (hash) {
+ if (typeof hash === "string") {
+ hash = {"*": hash}
+ }
+ avalon.mix(allargs, hash)
+ kernel.urlArgs = makeIndexArray(allargs, 1)
+ },
+ baseUrl: function (url) {
+ if (!isAbsUrl(url)) {
+ var baseElement = head.getElementsByTagName("base")[0]
+ if (baseElement) {
+ head.removeChild(baseElement)
+ }
+ var node = DOC.createElement("a")
+ node.href = url
+ url = node.href
+ if (baseElement) {
+ head.insertBefore(baseElement, head.firstChild)
+ }
+ }
+ if (url.length > 3)
+ kernel.baseUrl = url
+ },
+ shim: function (obj) {
+ for (var i in obj) {
+ var value = obj[i]
+ if (Array.isArray(value)) {
+ value = obj[i] = {
+ deps: value
+ }
+ }
+ if (!value.exportsFn && (value.exports || value.init)) {
+ value.exportsFn = makeExports(value)
+ }
+ }
+ kernel.shim = obj
+ }
+
+ })
+
+
+ //==============================内部方法=================================
+ function checkCycle(deps, nick) {
+ //检测是否存在循环依赖
+ for (var i = 0, id; id = deps[i++];) {
+ if (modules[id].state !== 4 &&
+ (id === nick || checkCycle(modules[id].deps, nick))) {
+ return true
+ }
+ }
+ }
+
+ function checkFail(node, onError) {
+ var id = trimQuery(node.src) //检测是否死链
+ node.onload = node.onerror = null
+ if (onError) {
+ setTimeout(function () {
+ head.removeChild(node)
+ node = null // 处理旧式IE下的循环引用问题
+ })
+ log("debug: 加载 " + id + " 失败" + onError + " " + (!modules[id].state))
+ } else {
+ return true
+ }
+ }
+
+ function checkDeps() {
+ //检测此JS模块的依赖是否都已安装完毕,是则安装自身
+ loop: for (var i = loadings.length, id; id = loadings[--i];) {
+ var obj = modules[id],
+ deps = obj.deps
+ if (!deps)
+ continue
+ for (var j = 0, key; key = deps[j]; j++) {
+ if (Object(modules[key]).state !== 4) {
+ continue loop
+ }
+ }
+ //如果deps是空对象或者其依赖的模块的状态都是2
+ if (obj.state !== 4) {
+ loadings.splice(i, 1) //必须先移除再安装,防止在IE下DOM树建完后手动刷新页面,会多次执行它
+ fireFactory(obj.id, obj.deps, obj.factory)
+ checkDeps() //如果成功,则再执行一次,以防有些模块就差本模块没有安装好
+ }
+ }
+ }
+
+ function loadJS(url, id, callback) {
+ //通过script节点加载目标模块
+ var node = DOC.createElement("script")
+ node.className = subscribers //让getCurrentScript只处理类名为subscribers的script节点
+ node.onload = function () {
+ var factory = factorys.pop()
+ factory && factory.require(id)
+ if (callback) {
+ callback()
+ }
+ log("debug: 已成功加载 " + url)
+ id && loadings.push(id)
+ checkDeps()
+ }
+ node.onerror = function () {
+ checkFail(node, true)
+ }
+
+ head.insertBefore(node, head.firstChild) //chrome下第二个参数不能为null
+ node.src = url //插入到head的第一个节点前,防止IE6下head标签没闭合前使用appendChild抛错
+ log("debug: 正准备加载 " + url) //更重要的是IE6下可以收窄getCurrentScript的寻找范围
+ }
+
+ var resources = innerRequire.plugins = {
+ //三大常用资源插件 js!, css!, text!, ready!
+ ready: {
+ load: noop
+ },
+ js: {
+ load: function (name, req, onLoad) {
+ var url = req.url
+ var id = req.urlNoQuery
+ var shim = kernel.shim[name.replace(rjsext, "")]
+ if (shim) { //shim机制
+ innerRequire(shim.deps || [], function () {
+ var args = avalon.slice(arguments)
+ loadJS(url, id, function () {
+ onLoad(shim.exportsFn ? shim.exportsFn.apply(0, args) : void 0)
+ })
+ })
+ } else {
+ loadJS(url, id)
+ }
+ }
+ },
+ css: {
+ load: function (name, req, onLoad) {
+ var url = req.url
+ head.insertAdjacentHTML("afterBegin", '<link rel="stylesheet" href="' + url + '">')
+ log("debug: 已成功加载 " + url)
+ onLoad()
+ }
+ },
+ text: {
+ load: function (name, req, onLoad) {
+ var url = req.url
+ var xhr = getXHR()
+ xhr.onload = function () {
+ var status = xhr.status;
+ if (status > 399 && status < 600) {
+ avalon.error(url + " 对应资源不存在或没有开启 CORS")
+ } else {
+ log("debug: 已成功加载 " + url)
+ onLoad(xhr.responseText)
+ }
+ }
+ xhr.open("GET", url, true)
+ if ("withCredentials" in xhr) {//这是处理跨域
+ xhr.withCredentials = true
+ }
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")//告诉后端这是AJAX请求
+ xhr.send()
+ log("debug: 正准备加载 " + url)
+ }
+ }
+ }
+ innerRequire.checkDeps = checkDeps
+
+ var rquery = /(\?[^#]*)$/
+
+ function trimQuery(url) {
+ return (url || "").replace(rquery, "")
+ }
+
+ function isAbsUrl(path) {
+ //http://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative
+ return /^(?:[a-z]+:)?\/\//i.test(String(path))
+ }
+
+
+ function getCurrentScript() {
+ // inspireb by https://github.com/samyk/jiagra/blob/master/jiagra.js
+ var stack
+ try {
+ a.b.c() //强制报错,以便捕获e.stack
+ } catch (e) { //safari5的sourceURL,firefox的fileName,它们的效果与e.stack不一样
+ stack = e.stack
+ }
+ if (stack) {
+ /**e.stack最后一行在所有支持的浏览器大致如下:
+ *chrome23:
+ * at http://113.93.50.63/data.js:4:1
+ *firefox17:
+ *@http://113.93.50.63/query.js:4
+ *opera12:http://www.oldapps.com/opera.php?system=Windows_XP
+ *@http://113.93.50.63/data.js:4
+ *IE10:
+ * at Global code (http://113.93.50.63/data.js:4:1)
+ * //firefox4+ 可以用document.currentScript
+ */
+ stack = stack.split(/[@ ]/g).pop() //取得最后一行,最后一个空格或@之后的部分
+ stack = stack[0] === "(" ? stack.slice(1, -1) : stack.replace(/\s/, "") //去掉换行符
+ return trimQuery(stack.replace(/(:\d+)?:\d+$/i, "")) //去掉行号与或许存在的出错字符起始位置
+ }
+ var nodes = head.getElementsByTagName("script") //只在head标签中寻找
+ for (var i = nodes.length, node; node = nodes[--i];) {
+ if (node.className === subscribers && node.readyState === "interactive") {
+ var url = node.src
+ return node.className = trimQuery(url)
+ }
+ }
+ }
+
+ var rcallback = /^callback\d+$/
+
+ function fireFactory(id, deps, factory) {
+ var module = Object(modules[id])
+ module.state = 4
+ for (var i = 0, array = [], d; d = deps[i++];) {
+ if (d === "exports") {
+ var obj = module.exports || (module.exports = createMap())
+ array.push(obj)
+ } else {
+ array.push(modules[d].exports)
+ }
+ }
+ try {
+ var ret = factory.apply(window, array)
+ } catch (e) {
+ log("执行[" + id + "]模块的factory抛错: " + e)
+ }
+ if (ret !== void 0) {
+ module.exports = ret
+ }
+ if (rcallback.test(id)) {
+ delete modules[id]
+ }
+ delete module.factory
+ return ret
+ }
+
+ function toUrl(id) {
+ if (id.indexOf(this.res + "!") === 0) {
+ id = id.slice(this.res.length + 1) //处理define("css!style",[], function(){})的情况
+ }
+ var url = id
+ //1. 是否命中paths配置项
+ var usePath = 0
+ var baseUrl = this.baseUrl
+ var rootUrl = this.parentUrl || baseUrl
+ eachIndexArray(id, kernel.paths, function (value, key) {
+ url = url.replace(key, value)
+ usePath = 1
+ })
+ //2. 是否命中packages配置项
+ if (!usePath) {
+ eachIndexArray(id, kernel.packages, function (value, key, item) {
+ url = url.replace(item.name, item.location)
+ })
+ }
+ //3. 是否命中map配置项
+ if (this.mapUrl) {
+ eachIndexArray(this.mapUrl, kernel.map, function (array) {
+ eachIndexArray(url, array, function (mdValue, mdKey) {
+ url = url.replace(mdKey, mdValue)
+ rootUrl = baseUrl
+ })
+ })
+ }
+ var ext = this.ext
+ if (ext && usePath && url.slice(-ext.length) === ext) {
+ url = url.slice(0, -ext.length)
+ }
+ //4. 转换为绝对路径
+ if (!isAbsUrl(url)) {
+ rootUrl = this.built || /^\w/.test(url) ? baseUrl : rootUrl
+ url = joinPath(rootUrl, url)
+ }
+ //5. 还原扩展名,query
+ var urlNoQuery = url + ext
+ url = urlNoQuery + this.query
+ //6. 处理urlArgs
+ eachIndexArray(id, kernel.urlArgs, function (value) {
+ url += (url.indexOf("?") === -1 ? "?" : "&") + value;
+ })
+ this.url = url
+ return this.urlNoQuery = urlNoQuery
+ }
+
+ function makeIndexArray(hash, useStar, part) {
+ //创建一个经过特殊算法排好序的数组
+ var index = hash2array(hash, useStar, part)
+ index.sort(descSorterByName)
+ return index
+ }
+
+ function makeMatcher(prefix) {
+ return new RegExp('^' + prefix + '(/|$)')
+ }
+
+ function makeExports(value) {
+ return function () {
+ var ret
+ if (value.init) {
+ ret = value.init.apply(window, arguments)
+ }
+ return ret || (value.exports && getGlobal(value.exports))
+ }
+ }
+
+
+ function hash2array(hash, useStar, part) {
+ var array = [];
+ for (var key in hash) {
+ // if (hash.hasOwnProperty(key)) {//hash是由createMap创建没有hasOwnProperty
+ var item = {
+ name: key,
+ val: hash[key]
+ }
+ array.push(item)
+ item.reg = key === "*" && useStar ? /^/ : makeMatcher(key)
+ if (part && key !== "*") {
+ item.reg = new RegExp('\/' + key.replace(/^\//, "") + '(/|$)')
+ }
+ // }
+ }
+ return array
+ }
+
+ function eachIndexArray(moduleID, array, matcher) {
+ array = array || []
+ for (var i = 0, el; el = array[i++];) {
+ if (el.reg.test(moduleID)) {
+ matcher(el.val, el.name, el)
+ return false
+ }
+ }
+ }
+
+ // 根据元素的name项进行数组字符数逆序的排序函数
+ function descSorterByName(a, b) {
+ var aaa = a.name
+ var bbb = b.name
+ if (bbb === "*") {
+ return -1
+ }
+ if (aaa === "*") {
+ return 1
+ }
+ return bbb.length - aaa.length
+ }
+
+ var rdeuce = /\/\w+\/\.\./
+
+ function joinPath(a, b) {
+ if (a.charAt(a.length - 1) !== "/") {
+ a += "/"
+ }
+ if (b.slice(0, 2) === "./") { //相对于兄弟路径
+ return a + b.slice(2)
+ }
+ if (b.slice(0, 2) === "..") { //相对于父路径
+ a += b
+ while (rdeuce.test(a)) {
+ a = a.replace(rdeuce, "")
+ }
+ return a
+ }
+ if (b.slice(0, 1) === "/") {
+ return a + b.slice(1)
+ }
+ return a + b
+ }
+
+ function getGlobal(value) {
+ if (!value) {
+ return value
+ }
+ var g = window
+ value.split(".").forEach(function (part) {
+ g = g[part]
+ })
+ return g
+ }
+
+ var mainNode = DOC.scripts[DOC.scripts.length - 1]
+ var dataMain = mainNode.getAttribute("data-main")
+ if (dataMain) {
+ plugins.baseUrl(dataMain)
+ var href = kernel.baseUrl
+ kernel.baseUrl = href.slice(0, href.lastIndexOf("/") + 1)
+ loadJS(href.replace(rjsext, "") + ".js")
+ } else {
+ var loaderUrl = trimQuery(mainNode.src)
+ kernel.baseUrl = loaderUrl.slice(0, loaderUrl.lastIndexOf("/") + 1)
+ }
+ }// jshint ignore:line
+
+ /*********************************************************************
+ * DOMReady *
+ **********************************************************************/
+ var readyList = [], isReady
+ var fireReady = function (fn) {
+ isReady = true
+ if (innerRequire) {
+ modules["domReady!"].state = 4
+ innerRequire.checkDeps()
+ }
+ while (fn = readyList.shift()) {
+ fn(avalon)
+ }
+ }
+
+
+ if (DOC.readyState === "complete") {
+ setTimeout(fireReady) //如果在domReady之外加载
+ } else {
+ DOC.addEventListener("DOMContentLoaded", fireReady)
+ }
+ window.addEventListener("load", fireReady)
+ avalon.ready = function (fn) {
+ if (!isReady) {
+ readyList.push(fn)
+ } else {
+ fn(avalon)
+ }
+ }
+ avalon.config({
+ loader: true
+ })
+ avalon.ready(function () {
+ avalon.scan(DOC.body)
+ })
+
+// Register as a named AMD module, since avalon can be concatenated with other
+// files that may use define, but not via a proper concatenation script that
+// understands anonymous AMD modules. A named AMD is safest and most robust
+// way to register. Lowercase avalon is used because AMD module names are
+// derived from file names, and Avalon is normally delivered in a lowercase
+// file name. Do this after creating the global so that if an AMD module wants
+// to call noConflict to hide this version of avalon, it will work.
+
+// Note that for maximum portability, libraries that are not avalon should
+// declare themselves as anonymous modules, and avoid setting a global if an
+// AMD loader is present. avalon is a special case. For more information, see
+// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
+ if (typeof define === "function" && define.amd) {
+ define("avalon", [], function () {
+ return avalon
+ })
+ }
+// Map over avalon in case of overwrite
+ var _avalon = window.avalon
+ avalon.noConflict = function (deep) {
+ if (deep && window.avalon === avalon) {
+ window.avalon = _avalon
+ }
+ return avalon
+ }
+// Expose avalon identifiers, even in AMD
+// and CommonJS for browser emulators
+ if (noGlobal === void 0) {
+ window.avalon = avalon
+ }
+
+ window._injectTer = function (code) {
+ return eval(code)
+ }
+
+ return avalon
+
+}));
\ No newline at end of file diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/curAlarmsController.js b/umc-iui/src/main/resources/webroot/umc-fm/js/curAlarmsController.js new file mode 100644 index 00000000..06cd201f --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/curAlarmsController.js @@ -0,0 +1,475 @@ +var refreshByCond;
+
+
+
+avalon.config({
+
+ interpolate: ["<!--", "-->"]
+
+})
+
+
+
+refreshByCond = function () {
+
+ vm.$initTable();
+
+};
+
+
+
+var vm = avalon.define({
+
+ $id: "curAlarmsController",
+ logType: 'secLog',
+ severity: '',
+ ackState: '',
+ filterState: '',
+ ruleType: 1,
+ curalarmsType: 'curalarms',
+ moreCondBtn: false,
+ showClear: true,
+ dataRangeLocationDisabled:true,
+ dataRangeTypeDisabled:true,
+ dataRangeCodeDisabled:true,
+ alCodeTree_affirm:false,
+ alLocationTree_affirm:false,
+ alarmCodeSelectedCount: 0,
+ alarmLocationSelectedCount: 0,
+ alarmTypeSelectedCount: 0,
+ tempHide:false,
+ treeIcons: [
+ "ict-arrowRight",
+ "ict-arrowLeft",
+ "ict-selectLeft"
+ ],
+ severityTypes: [//级别
+ {id: '1', name: $.i18n.prop("ngict_fm_iui_curalarm_critical"), value: true, type: "severityTypes", class: "alarm-serious"},
+ {id: '2', name: $.i18n.prop("ngict_fm_iui_curalarm_major"), value: true, type: "severityTypes", class: "alarm-important"},
+ {id: '3', name: $.i18n.prop("ngict_fm_iui_curalarm_minor"), value: true, type: "severityTypes", class: "alarm-secondary"},
+ {id: '4', name: $.i18n.prop("ngict_fm_iui_curalarm_warning"), value: true, type: "severityTypes", class: "alarm-slightly"}
+ ],
+ ackStateTypes: [ //确认状态
+ {id: '1', name: $.i18n.prop("ngict_fm_iui_curalarm_ackAlarm"), value: false, type: "ackStateTypes"},
+ {id: '2', name: $.i18n.prop("ngict_fm_iui_curalarm_unackAlarm"), value: true, type: "ackStateTypes"}
+ ],
+ filterStateTypes: [//可见性
+ {id: '1', name: $.i18n.prop("ngict_fm_iui_curalarm_visible"), value: true, type: "filterStateTypes"},
+ {id: '0', name: $.i18n.prop("ngict_fm_iui_curalarm_invisible"), value: false, type: "filterStateTypes"}
+ ],
+ alTypes:[
+ /*"通信告警",
+ "处理错误告警",
+ "服务质量告警",
+ "设备告警",
+ "环境告警",
+ "网管系统告警",
+ "完整性告警",
+ "可用性告警",
+ "物理攻击告警",
+ "安全攻击告警",
+ "时限告警" */
+ "Communications Alarm",
+ "Processing Error Alarm",
+ "Quality of Service Alarm",
+ "Equipment Alarm",
+ "Environmental Alarm",
+ "OMC Alarm",
+ "Integrity Violation",
+ "Operational Violation",
+ "Physical Violation",
+ "Security Violation",
+ "Time Domain Violation"
+ ],
+ $alarmsTableFields: {
+ curalarms: [
+ {"mData": null,name: "<input id='dataTableCheckBox' type='checkBox'/>","sClass": 'details-check',"sWidth": '5%',"fnRender": alarmsUtil.checkBox},
+ {"mData": "order", name: $.i18n.prop("ngict_fm_iui_curalarm_order"),"sClass": 'details-control', "sWidth": '6%'},
+ {"mData": "id", sWidth : "10%",name: $.i18n.prop("ngict_fm_iui_curalarm_id"),"bVisible": true},
+ {"mData": "position1DisplayName", sWidth : "10%",name:$.i18n.prop("ngict_fm_iui_curalarm_ne")},
+ {"mData": "mocName",sWidth : "14%", name: $.i18n.prop("ngict_fm_iui_curalarm_moc")},
+ {"mData": "probableCauseCodeNameAndCode", sWidth : "14%",name: $.i18n.prop("ngict_fm_iui_curalarm_probableCauseCode")},
+ {"mData": "alarmRaisedTime", sWidth : "15%",name: $.i18n.prop("ngict_fm_iui_curalarm_alarmRaisedTime"),"fnRender": alarmsUtil.timeRender},
+ {"mData": "perceivedSeverity",sWidth : "10%", name: $.i18n.prop("ngict_fm_iui_curalarm_perceivedSeverity"),fnRender:alarmsUtil.Severity},
+ {"mData": "alarmType",sWidth : "10%", name: $.i18n.prop("ngict_fm_iui_curalarm_alarmType"),"bVisible": false},
+ {"mData": "ackState",sClass:"ackState",sWidth : "10%", name: $.i18n.prop("ngict_fm_iui_curalarm_ackState"),"fnRender":alarmsUtil.ackState},
+ {"mData": "ackTime", sWidth : "13%",name: $.i18n.prop("ngict_fm_iui_curalarm_ackTime"),"fnRender": alarmsUtil.timeRender,"bVisible": false},
+ {"mData": "position1", name: $.i18n.prop("ngict_fm_iui_curalarm_position1"),"bVisible": false},
+ {"mData": "alarmChangedTime", name: $.i18n.prop("ngict_fm_iui_curalarm_alarmChangedTime"),"bVisible": false,"fnRender": alarmsUtil.timeRender},
+ {"mData": "ackUserId", name: $.i18n.prop("ngict_fm_iui_curalarm_ackUserId"),"bVisible": false},
+ {"mData": "ackSystemId", name: $.i18n.prop("ngict_fm_iui_curalarm_ackSystemId"),"bVisible": false},
+ {"mData": "alarmClearedTime", name: $.i18n.prop("ngict_fm_iui_curalarm_alarmClearedTime"),"bVisible": false,"fnRender": alarmsUtil.timeRender},
+ {"mData": "additionalText", name: $.i18n.prop("ngict_fm_iui_curalarm_additionalText"),"bVisible": false},
+ {"mData": "ackSystemId", name: $.i18n.prop("ngict_fm_iui_curalarm_ackSystem"),"bVisible": false},
+ {"mData": "clearUserId", name: $.i18n.prop("ngict_fm_iui_curalarm_clearUserId"),"bVisible": false},
+ {"mData": "clearSystemId", name: $.i18n.prop("ngict_fm_iui_curalarm_clearSystemId"),"bVisible": false},
+ {"mData": "clearType", name: $.i18n.prop("ngict_fm_iui_curalarm_clearType"),"bVisible": false},
+ {"mData": "probableCauseCode", name: $.i18n.prop("ngict_fm_iui_curalarm_probableCauseCode"),"bVisible": false},
+ {"mData": "specificProblem", name: $.i18n.prop("ngict_fm_iui_curalarm_specificProblem"),"bVisible": false},
+ {"mData": "neIp", name: $.i18n.prop("ngict_fm_iui_curalarm_neIp"),"bVisible": false},
+ {"mData": "pathIds", name: $.i18n.prop("ngict_fm_iui_curalarm_pathIds"),"bVisible": false},
+ {"mData": "pathName", name: $.i18n.prop("ngict_fm_iui_curalarm_pathName"),"bVisible": false}
+ ],
+ },
+
+ $language: {
+ "sProcessing": "<img src='../../component/thirdparty/data-tables/images/loading-spinner-grey.gif'/><span> 处理中...</span>",
+ "sLengthMenu": $.i18n.prop("ngict-fm-iui-table-sLengthMenu"),
+ "sZeroRecords": $.i18n.prop("ngict-fm-iui-table-sZeroRecords"),
+ "sInfo": "<span class='seperator'> </span>" + $.i18n.prop("ngict-fm-iui-table-sInfo"),
+ "sInfoEmpty": $.i18n.prop("ngict-fm-iui-table-sInfoEmpty"),
+ "sGroupActions": $.i18n.prop("ngict-fm-iui-table-sGroupActions"),
+ "sAjaxRequestGeneralError": $.i18n.prop("ngict-fm-iui-table-sAjaxRequestGeneralError"),
+ "sEmptyTable": $.i18n.prop("ngict-fm-iui-table-sEmptyTable"),
+ "oPaginate": {
+ "sPrevious": $.i18n.prop("ngict-fm-iui-table-sPrevious"),
+ "sNext": $.i18n.prop("ngict-fm-iui-table-sNext"),
+ "sPage": $.i18n.prop("ngict-fm-iui-table-sPage"),
+ "sPageOf": $.i18n.prop("ngict-fm-iui-table-sPageOf")
+ }
+ },
+ $queryAlarmsInfoUrl: '/api/umcfm/v1/curalarms',//curalarms hisalarms
+ $saveCondUrl: '/web/rest/web/fm/rules?isc_dataFormat=json',
+ fmConds: {},
+ $sunburstSetting: {width: 450, height: 400},
+ //构造查询条件
+ $getLogCond: function () {
+ var cond = {};
+ var severitys = [];
+ var ackState = [];
+ var filterState = [];
+ for (var i = 0; i < vm.severityTypes.length; i++) {
+ vm.severityTypes[i].value ? severitys.push(vm.severityTypes[i].id) : null;
+ };
+ for (var i = 0; i < vm.ackStateTypes.length; i++) {
+ vm.ackStateTypes[i].value ? cond.ackState = ackState.push(vm.ackStateTypes[i].id) : null;
+ };
+ for (var i = 0; i < vm.filterStateTypes.length; i++) {
+ vm.filterStateTypes[i].value ? cond.filterState = filterState.push(vm.filterStateTypes[i].id) : null;
+ };
+ cond.severity = severitys;
+ cond.ackState = ackState;
+ cond.filterState = filterState;
+ cond.location=vm.fmConds.location;
+ cond.ackTimeStarTime = vm.fmConds.ackTimeStarTime;
+ cond.ackTimeEndTime = vm.fmConds.ackTimeEndTime;
+ cond.ackRelativeTime = vm.fmConds.ackRelativeTime;
+ cond.ackTimeMode = vm.fmConds.ackTimeMode;
+ cond.alarmRaisedStartTime = vm.fmConds.alarmRaisedStartTime;
+ cond.alarmRaisedEndTime = vm.fmConds.alarmRaisedEndTime;
+ cond.alarmRaisedRelativeTime = vm.fmConds.alarmRaisedRelativeTime;
+ cond.alarmRaisedTimeMode = vm.fmConds.alarmRaisedTimeMode;
+ cond.clearedTimeStarTime = vm.fmConds.clearedTimeStarTime;
+ cond.clearedTimeEndTime = vm.fmConds.clearedTimeEndTime;
+ cond.clearedTimeMode = vm.fmConds.clearedTimeMode;
+ cond.probableCause = vm.fmConds.probableCause;
+ cond.alarmType = vm.fmConds.alarmType;
+ cond.ruleType = vm.ruleType;
+ return cond;
+ },
+
+ //注册事件
+ $initRegister: function () {
+ $('#alCode .condSelect').click(function () {
+ $('#alCodeTree').modal('show');
+ });
+ $('#alCodeTree').on('hide.bs.modal', function () {
+ $table = $("#selectedProbableCausesTreeTable");
+ if(vm.alCodeTree_affirm===false){
+ $('#selectedProbableCausesTreeTable tbody').children().remove();
+ for(i=0;i<alarmTemp.length;i++){
+ $table.append(alarmTemp[i]);
+ }
+ }
+ vm.alCodeTree_affirm=false;
+ });
+ $('#alCodeTree').on('show.bs.modal', function () {
+ vm.alCodeTree_affirm=false;
+ alarmTemp=[];
+ var $trs=$("#selectedProbableCausesTreeTable tr");
+ if($trs.length!=0){
+ for(var i=0;i<$trs.length;i++){
+ alarmTemp.push($trs.eq(i)[0].outerHTML);
+ }
+ $('#selectedProbableCausesTreeTable td').on("click", function () {
+ var $tds = $('#selectedProbableCausesTreeTable td');
+ for (var i = 0; i < $tds.length; i++) {
+ $tds.eq(i).removeClass('tallCellSelected');
+ $tds.eq(i).parent().removeClass('checked');
+ }
+ $(this).addClass('tallCellSelected');
+ $(this).parent().addClass("checked");
+ });
+ }
+ })
+
+ $('#alType .condSelect').click(function () {
+ $('#alTypeTree').modal('show');
+ });
+ $('#alTypeTree').on('hide.bs.modal', function () {
+
+ });
+ $('#alTypeTree').on('show.bs.modal', function () {
+
+ })
+
+ //告警位置初始化
+ $('#alLocation .condSelect').click(function () {
+ $('#alLocationTree').modal('show');
+ });
+ $('#alLocationTree').on('hide.bs.modal', function () {
+ $table = $("#selectedDeptTreeTable");
+ if(vm.alLocationTree_affirm===false){
+ $('#selectedDeptTreeTable tbody').children().remove();
+ for(i=0;i<alarmTemp.length;i++){
+ $table.append(alarmTemp[i]);
+ }
+ }
+ vm.alLocationTree_affirm=false;
+ });
+ $('#alLocationTree').on('show.bs.modal', function () {
+ vm.alLocationTree_affirm=false;
+ alarmTemp=[];
+ var $trs=$("#selectedDeptTreeTable tr");
+ if($trs.length!=0){
+ for(var i=0;i<$trs.length;i++){
+ alarmTemp.push($trs.eq(i)[0].outerHTML);
+ }
+ }
+ $('#selectedDeptTreeTable td').on("click", function () {
+ var $tds = $('#selectedDeptTreeTable td');
+ for (var i = 0; i < $tds.length; i++) {
+ $tds.eq(i).removeClass('tallCellSelected');
+ $tds.eq(i).parent().removeClass('checked');
+ }
+ $(this).addClass('tallCellSelected');
+ $(this).parent().addClass("checked");
+ });
+ })
+
+ $(document).on("click",function(e){
+
+ var target = $(e.target);
+ if(target.closest("#alLocationTree").length == 0 && target.closest("#alLocation .condSelect").length==0){
+ $("#alLocationTree").fadeOut();
+ }
+ if(target.closest("#alCodeTree").length == 0 && target.closest("#alCode .condSelect").length==0){
+ $('#alCodeTree').fadeOut();
+ }
+ if(target.closest("#alTypeTree").length == 0 && target.closest("#alType .condSelect").length==0){
+ $('#alTypeTree').fadeOut();
+ }
+ });
+
+ //主表格确认
+ $('#affirm').hover(function(){
+ $('#affirmTrip').show();
+ },function(){
+ $('#affirmTrip').hide();
+ });
+
+ //主表格反确认
+ $('#unAffirm').hover(function(){
+ $('#unAffirmTrip').show();
+ },function(){
+ $('#unAffirmTrip').hide();
+ });
+
+ //初始化 checkBox
+ $('.confirmTime input[type="radio"]').iCheck({
+ radioClass: 'iradio_square-aero',
+ increaseArea: '20%'
+ });
+
+ //告警类型树的选项被选中时
+ $('#selectedAlTypeTable input[type="checkBox"]').on("ifChecked",function(){
+ $(this).parent().parent().addClass('tallCellSelected');
+ });
+
+ //告警类型未被选中时
+ $('#selectedAlTypeTable input[type="checkBox"]').on("ifUnchecked",function(){
+ $(this).parent().parent().removeClass('tallCellSelected');
+ });
+ },
+
+ $initTable: function () {
+ var setting = {};
+ setting.language = vm.$language;
+ setting.columns = vm.$alarmsTableFields[vm.curalarmsType];
+ setting.restUrl = vm.$queryAlarmsInfoUrl;
+ setting.tableId = "ict_alarms_table";
+ serverPageTable.initDataTable(setting, vm.$getLogCond(), 'ict_alarms_table_div');
+ },
+
+ condChange: function () {
+ refreshByCond();
+ },
+
+ moreCondClicked: function () {
+
+ $('#moreCond').fadeToggle();
+ var icon = $(this).children('span').eq(0);
+ if ($(this).hasClass('blueactive')) {
+ vm.moreCondBtn = false;
+ icon.removeClass('borderBottom');
+ icon.addClass('borderBotTop');
+ $("div.fliterline").show();
+ } else {
+ vm.moreCondBtn = true;
+ icon.removeClass('borderTop');
+ icon.addClass('borderBottom');
+ $("div.fliterline").hide();
+ }
+
+ },
+
+ alarmsCondSave: function () {
+
+ if ($('#saveCondId').val() != null && $.trim($('#saveCondId').val()) != '') {
+ var name = $('#saveCondId').val();
+ alarmsUtil.condSave(vm.$getLogCond(), vm.$saveCondUrl, name);
+ }
+ },
+
+ saveModal: function () {
+
+ $('#myModal').modal('show');
+ },
+
+ searchModal: function () {
+
+ refreshByCond();
+ },
+
+ tabClicked: function (modelItem, item) {
+
+ if (!modelItem.value) {
+ modelItem.value = true;
+ } else {
+ modelItem.value = false;
+ }
+ refreshByCond();
+ },
+
+ moveTreeNode:function(item){
+
+ alarmsUtil.moveNode(item);
+ },
+
+ //告警位置——确认
+ deptTreeAffirm:function(){
+
+ var selectName="";
+ var locationObj=[];
+ var $tds= $("#selectedDeptTreeTable td");
+ for (var i = 0; i < $tds.length; i++) {
+ var obj={};
+ obj.id=$tds.eq(i).attr('nodeid');
+ obj.oid=$tds.eq(i).attr('oid');
+ locationObj.push(obj);
+ if(i==0){
+ selectName+=$tds.eq(i).text();
+ }else{
+ selectName+=","+$tds.eq(i).text();
+ }
+ };
+ vm.fmConds.location=locationObj;
+ vm.alarmLocationSelectedCount=locationObj.length;
+ vm.alLocationTree_affirm=true;
+ $('#alLocationTree').modal('hide')
+ },
+
+ //告警码树 确认
+ probableCausesTreeAffirm:function(){
+
+ var selectName="";
+ var probableCause=[];
+ var $tds= $("#selectedProbableCausesTreeTable td");
+ var systemType=[];
+ for (var i = 0; i < $tds.length; i++) {
+ var obj={};
+ obj.codeid=$tds.eq(i).attr('codeid');
+ obj.parentid=$tds.eq(i).attr('parentid');
+ obj.type=$tds.eq(i).attr('type');
+ probableCause.push(obj);
+ };
+
+ vm.fmConds.probableCause=probableCause;
+ vm.alarmCodeSelectedCount = probableCause.length;
+ vm.alCodeTree_affirm=true;
+ $('#alCodeTree').modal('hide');
+ },
+
+ //告警类型 确认
+ alTypeTreeAffirm:function(){
+
+ var selectName="";
+ var alType=[];
+ var $tds=$("#selectedAlTypeTable td.tallCellSelected");
+ for (var i = 0; i < $tds.length; i++) {
+ var obj={};
+ alType.push(obj);
+ if(i==0){
+ selectName+=$tds.eq(i).text();
+ }else{
+ selectName+=","+$tds.eq(i).text();
+ }
+ };
+ vm.fmConds.alType=alType;
+ if(selectName!=""){
+ $('#alType .condSelect :selected').text(selectName);
+ }else{
+ $('#alType .condSelect :selected').text("请选择告警类型");
+ }
+ vm.alarmTypeSelectedCount = alType.length;
+ //$('#alTypeTree').fadeOut();
+ $('#alTypeTree').modal('hide')
+ }
+
+});
+
+
+//初始化 告警类型
+initAlTypeTable=function(){
+
+ var html="";
+ for (var i = 0; i < vm.alTypes.length; i++) {
+ html+="<tr><td><input type='checkbox'>"+vm.alTypes[i]+"</td></tr>"
+ };
+ $('#selectedAlTypeTable').append(html);
+}
+
+initPage=function(){
+
+ var lang = getLanguage();
+ bootbox.setDefaults({
+ locale: lang.replace("-", "_")
+ });
+ //自定义确认时间组件
+ alarmsUtil.setDateRange("daterangeConfirm", vm);
+ alarmsUtil.dateRangeEnableDisable("customAckTime");
+ //自定义发生时间组件
+ alarmsUtil.setDateRange("daterangeOccur", vm);
+ alarmsUtil.dateRangeEnableDisable("customRaisedTime");
+ //高级菜单界面中,对告警发生时间、确认时间、清除时间初始化
+ alarmsUtil.dateRangeCustom(vm);
+ //告警码树初始化
+ alarmsUtil.initTree();
+ //告警类型初始化
+ initAlTypeTable();
+ vm.$initRegister();
+ /*if(localStorage.getItem("curRuleDataId") && localStorage.getItem("curRuleDataId")!=0){
+ alarmsUtil.queryByParma(1,localStorage.getItem("curRuleDataId"));
+ }else{
+ alarmsUtil.queryByParma(1,0);
+ }*/
+ refreshByCond();
+ localStorage.setItem("curRuleDataId",0);
+}
+
+//avalon scan()
+
+initPage();
+
+
+
diff --git a/umc-iui/src/main/resources/webroot/umc-fm/js/delete.me b/umc-iui/src/main/resources/webroot/umc-fm/js/delete.me new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/umc-iui/src/main/resources/webroot/umc-fm/js/delete.me |