o2oa api: o2-游戏厅捕鱼达人

source

/** ***** begin license block *****
 * |------------------------------------------------------------------------------|
 * | o2oa 活力办公 创意无限    o2.js                                                 |
 * |------------------------------------------------------------------------------|
 * | distributed under the agpl license:                                          |
 * |------------------------------------------------------------------------------|
 * | 游戏厅捕鱼达人 copyright © 2018, o2oa.net, o2server.io o2 team                              |
 * | all rights reserved.                                                         |
 * |------------------------------------------------------------------------------|
 *
 *  this file is part of o2oa.
 *
 *  o2oa is free software: you can redistribute it and/or modify
 *  it under the terms of the gnu affero general public license as published by
 *  the free software foundation, either version 3 of the license, or
 *  (at your option) any later version.
 *
 *  o2oa is distributed in the hope that it will be useful,
 *  but without any warranty; without even the implied warranty of
 *  merchantability or fitness for a particular purpose.  see the
 *  gnu affero general public license for more details.
 *
 *  you should have received a copy of the gnu general public license
 *  along with o2oa.  if not, see .
 *
 * ***** end license block ******/
/* load o2 core
 * |------------------------------------------------------------------------------|
 * |addready:     o2.addready(fn),                                                |
 * |------------------------------------------------------------------------------|
 * |load:         o2.load(urls, callback, reload)                                 |
 * |loadcss:      o2.loadcss(urls, dom, callback, reload, doc)                    |
 * |------------------------------------------------------------------------------|
 * |typeof:       o2.typeof(o)                                                    |
 * |------------------------------------------------------------------------------|
 * |uuid:         o2.uuid()                                                       |
 * |------------------------------------------------------------------------------|
 */
//element.firstelementchild polyfill
// (function(constructor) {
//     if (constructor &&
//         constructor.prototype &&
//         constructor.prototype.firstelementchild == null) {
//         object.defineproperty(constructor.prototype, 'firstelementchild', {
//             get: function() {
//                 var node, nodes = this.childnodes, i = 0;
//                 while (node = nodes[i  ]) {
//                     if (node.nodetype === 1) {
//                         return node;
//                     }
//                 }
//                 return null;
//             }
//         });
//     }
// })(window.node || window.element);
if (window.promise && !promise.any){
    promise.any = function(promises){
        if (!promises || !promises.length) return new promise();
        return new promise(function(resolve){
            var value = null;
            var resolved = false;
            var checkvalue = function(){
                if (resolved) resolve(value);
            };
            for (var i=0; i
         * @namespace o2
         * @o2cn 平台全局对象
         * @o2category web
         */
        this.o2 = window.o2 || {};
        /**
         * @summary 平台版本信息。
         * @member {object} version
         * @memberof o2
         * @o2syntax
         * //获取版本号
         * var v = o2.version.v;
         */
        this.o2.version = {
            "v": "o2oa",
            "build": "2022.09.13",
            "info": "o2oa 活力办公 创意无限. 游戏厅捕鱼达人 copyright © 2022, o2oa.net o2 team all rights reserved."
        };
        /**
         * @summary 平台运行环境。
         * @member {object} session
         * @memberof o2
         * @property {boolean}  isdebugger   是否是调试模式
         * @property {boolean}  ismobile   是否是移动端环境
         * @o2syntax
         * var debuggermode = o2.session.isdebugger;
         * var ismobile = o2.session.ismobile;
         */
        if (!this.o2.session) this.o2.session = {
            "isdebugger": _debug,
            "path": "../o2_core/o2"
        };
        /**
         * @summary 语言环境名称。
         * @member {string} language
         * @memberof o2
         * @o2syntax
         * var lp = o2.language;
         */
        this.o2.languagename = _lp;
        _lp = _lp.tolocalelowercase();
        if (supportedlanguages.indexof(_lp) == -1){
            _lp = _lp.substring(0, _lp.indexof('-'));
        }
        if (supportedlanguages.indexof(_lp) == -1) _lp = "zh-cn";
        this.o2.language = _lp;
        this.o2.splitstr = /\s*(?:,|;)\s*/;
        this.wrdp = this.o2;
        var debug = function (reload) {
            if (!o2.session.ismobile) {
                window.location.assign(_href   ((_href.indexof("?") == -1) ? "?" : "&")   "debugger");
            } else {
                if (!o2.session.isdebugger) {
                    o2.session.isdebugger = true;
                    if (o2.session.ismobile || layout.mobile) o2.load("../o2_lib/eruda/eruda.js");
                }
            }
        };
        /**
         * @summary 使平台进入调试模式。
         * @function debug
         * @memberof o2
         * @o2syntax
         * o2.debug();
         */
        this.o2.debug = debug;
        this.o2.runningrequestslist = [];
        var o2 = this.o2;
        var requestsend = xmlhttprequest.prototype.send;
        var requestopen = xmlhttprequest.prototype.open;
        xmlhttprequest.prototype.send = function(){
            var request = this;
            o2.runningrequestslist.push(request);
            request.addeventlistener("loadend", function(){
                o2.runningrequestslist.splice(o2.runningrequestslist.indexof(request, 1));
            });
            requestsend.apply(this, arguments);
        }
        xmlhttprequest.prototype.open = function(){
            var request = this;
            request.requestoptions = array.from(arguments);
            requestopen.apply(this, arguments);
        }
        var _attempt = function () {
            for (var i = 0, l = arguments.length; i < l; i  ) {
                try {
                    arguments[i]();
                    return arguments[i];
                } catch (e) {
                }
            }
            return null;
        };
        var _typeof = function (item) {
            if (item == null) return 'null';
            if (item.$family != null) return item.$family();
            if (item.constructor == window.array) return "array";
            if (item.nodename) {
                if (item.nodetype == 1) return 'element';
                if (item.nodetype == 3) return (/\s/).test(item.nodevalue) ? 'textnode' : 'whitespace';
            } else if (typeof item.length == 'number') {
                if (item.callee) return 'arguments';
            }
            return typeof item;
        };
        /**
         * @summary 判断一个任意参数的类型。
         * @function typeof
         * @memberof o2
         * @param {object} [obj] 要检查的对象
         * @return {string} 对象的类型,返回值:
         * 
'element' - 如果obj是一个dom element对象.
         * 'elements' - 如果obj是一个elements实例.
         * 'textnode' - 如果obj是一个dom text节点.
         * 'whitespace' - 如果obj是一个dom whitespace 节点.
         * 'arguments' - 如果obj是一个arguments对象.
         * 'array' - 如果obj是一个array数组.
         * 'object' - 如果obj是一个object对象.
         * 'string' - 如果obj是一个string.
         * 'number' - 如果obj是一个数字number.
         * 'date' - 如果obj是一个日期date.
         * 'boolean' - 如果obj是一个布尔值boolean.
         * 'function' - 如果obj是一个function.
         * 'regexp' - 如果obj是一个正则表达式.
         * 'collection' - 如果obj是一个原生html elements collection, 如childnodes or getelementsbytagname获取的对象.
         * 'window' - 如果obj是window对象.
         * 'document' - 如果obj是document对象.
         * 'domevent' - 如果obj是一个event.
         * 'null' - 如果obj是undefined, null, nan 或者 none.
         * 
* @o2syntax * o2.typeof(obj); * @example * var mystring = 'hello'; * o2.typeof(mystring); // returns "string" */ this.o2.typeof = _typeof; var _addlistener = function (dom, type, fn) { if (type == 'unload') { var old = fn, self = this; fn = function () { _removelistener(dom, 'unload', fn); old(); }; } if (dom.addeventlistener) dom.addeventlistener(type, fn, !!arguments[2]); else dom.attachevent('on' type, fn); }; var _removelistener = function (dom, type, fn) { if (dom.removeeventlistener) dom.removeeventlistener(type, fn, !!arguments[2]); else dom.detachevent('on' type, fn); }; //http request class var _request = (function () { var xmlhttp = function () { return new xmlhttprequest(); }; var msxml2 = function () { return new activexobject('msxml2.xmlhttp'); }; var msxml = function () { return new activexobject('microsoft.xmlhttp'); }; return _attempt(xmlhttp, msxml2, msxml); })(); this.o2.request = _request; var _returnbase = function (number, base) { return (number).tostring(base).touppercase(); }; var _getintegerbits = function (val, start, end) { var base16 = _returnbase(val, 16); var quadarray = new array(); var quadstring = ''; var i = 0; for (i = 0; i < base16.length; i ) { quadarray.push(base16.substring(i, i 1)); } for (i = math.floor(start / 4); i <= math.floor(end / 4); i ) { if (!quadarray[i] || quadarray[i] == '') quadstring = '0'; else quadstring = quadarray[i]; } return quadstring; }; var _rand = function (max) { return math.floor(math.random() * (max 1)); }; this.o2.addlistener = _addlistener; this.o2.removelistener = _removelistener; //uuid var _uuid = function () { var dg = new date(1582, 10, 15, 0, 0, 0, 0); var dc = new date(); var t = dc.gettime() - dg.gettime(); var tl = _getintegerbits(t, 0, 31); var tm = _getintegerbits(t, 32, 47); var thv = _getintegerbits(t, 48, 59) '1'; var csar = _getintegerbits(_rand(4095), 0, 7); var csl = _getintegerbits(_rand(4095), 0, 7); var n = _getintegerbits(_rand(8191), 0, 7) _getintegerbits(_rand(8191), 8, 15) _getintegerbits(_rand(8191), 0, 7) _getintegerbits(_rand(8191), 8, 15) _getintegerbits(_rand(8191), 0, 15); return tl tm thv csar csl n; }; /** * @summary 生成一个唯一的uuid。 * @function uuid * @memberof o2 * @o2syntax * var id = o2.uuid(); */ this.o2.uuid = _uuid; var _runcallback = function (callback, key, par, bind, promise_cb) { var b = bind || callback; if (!key) key = "success"; var cb; if (callback) { var type = o2.typeof(callback).tolowercase(); if (key.tolowercase() === "success" && type === "function") { cb = callback; } else { var name = ("on-" key).camelcase(); cb = (callback[name]) ? callback[name] : ((callback[key]) ? callback[key] : null); } } if (cb) return cb.apply(b, par); }; this.o2.runcallback = _runcallback; if (window.customevent) this.o2.customeventload = new customevent("o2load"); //load js, css, html adn all. var _getalloptions = function (options) { var doc = (options && options.doc) || document; if (!doc.unid) doc.unid = _uuid(); var type = (options && options.type) || "text/javascript"; return { "nocache": !!(options && options.nocache), "reload": !!(options && options.reload), "sequence": !!(options && options.sequence), "type": type, "doc": doc, "dom": (options && options.dom) || document.body, "module": (options && options.module) || null, "noconflict": (options && options.noconflict) || false, "url": !!(options && options.url), "bind": (options && options.bind) || null, "evalscripts": (options && options.evalscripts) || false, "baseurl": (options && options.baseurl) ? options.baseurl : "", "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend'debugger } }; var _getcssoptions = function (options) { var doc = (options && options.doc) || document; if (!doc.unid) doc.unid = _uuid(); return { "url": !!(options && options.url), "nocache": !!(options && options.nocache), "reload": !!(options && options.reload), "sequence": !!(options && options.sequence), "doc": doc, "dom": (options && options.dom) || null } }; var _getjsoptions = function (options) { var doc = (options && options.doc) || document; if (!doc.unid) doc.unid = _uuid(); var type = (options && options.type) || "text/javascript"; return { "nocache": !!(options && options.nocache), "reload": !!(options && options.reload), "sequence": (!(options && options.sequence == false)), "type": type, "baseurl": (options && options.baseurl) ? options.baseurl : "", "doc": doc } }; var _gethtmloptions = function (options) { var doc = (options && options.doc) || document; if (!doc.unid) doc.unid = _uuid(); return { "nocache": !!(options && options.nocache), "reload": !!(options && options.reload), "sequence": !!(options && options.sequence), "doc": doc, "dom": (options && options.dom) || null, "module": (options && options.module) || null, "noconflict": (options && options.noconflict) || false, "bind": (options && options.bind) || null, "evalscripts": (options && options.evalscripts) || false, "baseurl": (options && options.baseurl) ? options.baseurl : "", "position": (options && options.position) || "beforeend" //'beforebegin' 'afterbegin' 'beforeend' 'afterend' } }; _filterurl = function (url) { if (o2.base) { if (url.indexof(":") === -1) { var s = url.substring(0, url.indexof("/") 1); var r = url.substring(url.indexof("/") 1, url.length); if ("../" === s || "./" === s || "/" === s) { return s o2.base r; } else { return o2.base url } } } if (window.layout && layout.config && layout.config.urlmapping) { for (var k in layout.config.urlmapping) { var regex = new regexp(k); if (regex.test(url)) { return url.replace(regex, layout.config.urlmapping[k]); } } } return url; }; /** * @summary 解析平台内的url,如果配置了反向代理的路径转发,平台内的url需要通过filterurl解析后,才能得到正确的url。 * @see {@link https://www.o2oa.net/course/lskrtn.html?h=urlmapping|基于nginx快速集群部署-上下文分发} * @function filterurl * @memberof o2 * @param {string} [url] 要解析的url * @return {string} 解析后的url * @o2syntax * var url = o2.filter; * @example * * 当我们配置了按路径转发后,在portal.json中配置了urlmapping如: *
"urlmapping": {
         *      "qmx.o2oa.net:20020": "qmx.o2oa.net/dev/app",
         *      "qmx.o2oa.net:20030": "qmx.o2oa.net/dev/center"
         * },
* 在获取平台内部的url时,如附件的下载地址,需要通过filterurl解析。 * * var attachmenturl = "http://qmx.o2oa.net:20020/x_processplatform_assemble_surface/jaxrs/attachment/{attid}/work/{workid}"; * var url = o2.filter; * //return "http://qmx.o2oa.net/dev/app/x_processplatform_assemble_surface/jaxrs/attachment/{attid}/work/{workid}" */ this.o2.filterurl = _filterurl; var _xhr_get = function (url, success, failure, completed, sync) { var xhr = new _request(); url = _filter; xhr.open("get", url, !sync); var _checkcssloaded = function (_, err) { if (!(xhr.readystate == 4)) return; if (err) { if (completed) completed(xhr); return; } _removelistener(xhr, 'readystatechange', _checkcssloaded); _removelistener(xhr, 'load', _checkcssloaded); _removelistener(xhr, 'error', _checkcsserrorloaded); if (err) { if (failure) failure(xhr); return } var status = xhr.status; status = (status == 1223) ? 204 : status; if ((status >= 200 && status < 300)) if (success) success(xhr); else if ((status >= 300 && status < 400)) if (failure) failure(xhr); else failure(xhr); if (completed) completed(xhr); }; var _checkcsserrorloaded = function (err) { _checkcssloaded(err) }; if ("load" in xhr) _addlistener(xhr, "load", _checkcssloaded); if ("error" in xhr) _addlistener(xhr, "load", _checkcsserrorloaded); _addlistener(xhr, "readystatechange", _checkcssloaded); xhr.send(); }; this.o2.xhr_get = _xhr_get; var _loadsequence = function (ms, cb, op, n, thisloaded, loadsingle, uuid, fun) { loadsingle(ms[n], function (module) { if (module) thisloaded.push(module); n ; if (fun) fun(module); if (n === ms.length) { if (cb) cb(thisloaded); } else { _loadsequence(ms, cb, op, n, thisloaded, loadsingle, uuid, fun); } }, op, uuid); }; var _loaddisarray = function (ms, cb, op, thisloaded, loadsingle, uuid, fun) { var count = 0; for (var i = 0; i < ms.length; i ) { loadsingle(ms[i], function (module) { if (module) thisloaded.push(module); count ; if (fun) fun(module); if (count === ms.length) if (cb) cb(thisloaded); }, op, uuid); } }; //load js //use framework url var _frameworks = { "o2.core": ["../o2_core/o2/o2.core.js"], "o2.more": ["../o2_core/o2/o2.more.js"], "ie_adapter": ["../o2_core/o2/ie_adapter.js"], "jquery": ["../o2_lib/jquery/jquery.min.js"], "mootools": ["../o2_lib/mootools/mootools-1.6.0_all.js"], "ckeditor": ["../o2_lib/htmleditor/ckeditor4161/ckeditor.js"], "ckeditor5": ["../o2_lib/htmleditor/ckeditor5-12-1-0/ckeditor.js"], "raphael": ["../o2_lib/raphael/raphael.js"], "d3": ["../o2_lib/d3/d3.min.js"], "ace": ["../o2_lib/ace/src-min-noconflict/ace.js", "../o2_lib/ace/src-min-noconflict/ext-language_tools.js"], //"ace": ["../o2_lib/ace/src-noconflict/ace.js","../o2_lib/ace/src-noconflict/ext-language_tools.js"], "monaco": ["../o2_lib/vs/loader.js"], "jsbeautifier": ["../o2_lib/jsbeautifier/beautify.js"], "jsbeautifier_css": ["../o2_lib/jsbeautifier/beautify-css.js"], "jsbeautifier_html": ["../o2_lib/jsbeautifier/beautify-html.js"], "jsontemplate": ["../o2_lib/mootools/plugin/template.js"], "kity": ["../o2_lib/kityminder/kity/kity.js"], "kityminder": ["../o2_lib/kityminder/core/dist/kityminder.core.js"], "vue": ["../o2_lib/vue/vue.pro.js"], "vue_develop": ["../o2_lib/vue/vue.js"], "elementui": ["../o2_lib/vue/element/index.js"] }; var _loaded = {}; var _loadedcss = {}; var _loadedhtml = {}; var _loadcssrunning = {}; var _loadcssqueue = []; var _loadingmodules = {}; var _checkurl = function (url, base) { var urlstr = new uri(url, {base: base}).tostring(); return urlstr; } var _loadsingle = function (module, callback, op) { var url = module; if (op.baseurl) url = _check; var uuid = _uuid(); if (op.nocache) url = (url.indexof("?") !== -1) ? url "&v=" uuid : addr_uri "?v=" uuid; var key = encodeuricomponent(url op.doc.unid); if (!op.reload) if (_loaded[key]) { promise.resolve(_loaded[key]).then(function(o){ if (callback) callback(o); }); //if (callback) callback(); return; } if (_loadingmodules[key] && !op.reload) { if (!_loadingmodules[key].callbacks) _loadingmodules[key].callbacks = []; _loadingmodules[key].callbacks.push(callback); } else { _loadingmodules[key] = {callbacks: [callback]}; var head = (op.doc.head || op.doc.getelementsbytagname("head")[0] || op.doc.documentelement); var s = op.doc.createelement('script'); s.type = op.type || "text/javascript"; head.appendchild(s); s.id = uuid; s.src = this.o2.filter; var _checkscriptloaded = function (_, isabort, err) { if (isabort || !s.readystate || s.readystate === "loaded" || s.readystate === "complete") { var scriptobj = {"module": module, "id": uuid, "script": s, "doc": op.doc}; if (!err) _loaded[key] = scriptobj; _removelistener(s, 'readystatechange', _checkscriptloaded); _removelistener(s, 'load', _checkscriptloaded); _removelistener(s, 'error', _checkscripterrorloaded); if (!isabort || err) { if (err) { if (s) head.removechild(s); while (_loadingmodules[key].callbacks.length) { (_loadingmodules[key].callbacks.shift())(); } delete _loadingmodules[key]; //if (callback)callback(); } else { //head.removechild(s); while (_loadingmodules[key].callbacks.length) { (_loadingmodules[key].callbacks.shift())(scriptobj); } delete _loadingmodules[key]; //if (callback)callback(scriptobj); } } } }; var _checkscripterrorloaded = function (e, err) { console.log("error: load javascript module: " module); _checkscriptloaded(e, true, "error"); }; if ('onreadystatechange' in s) _addlistener(s, 'readystatechange', _checkscriptloaded); _addlistener(s, 'load', _checkscriptloaded); _addlistener(s, 'error', _checkscripterrorloaded); } }; var _load = function (urls, options, callback) { if (window.document && !window.importscripts) { var ms = (_typeof(urls) === "array") ? urls : [urls]; var op = (_typeof(options) === "object") ? _getjsoptions(options) : _getjsoptions(null); var cbk = (_typeof(options) === "function") ? options : callback; var cb = cbk; if (typeof define === 'function' && define.amd) { define.amd = false; cb = (cbk) ? function () { define.amd = true; cbk(); } : function () { define.amd = true; } } var modules = []; for (var i = 0; i < ms.length; i ) { var url = ms[i]; var module = _frameworks[url] || url; if (_typeof(module) === "array") { modules = modules.concat(module) } else { modules.push(module) } } var thisloaded = []; if (op.sequence) { _loadsequence(modules, cb, op, 0, thisloaded, _loadsingle); } else { _loaddisarray(modules, cb, op, thisloaded, _loadsingle); } } else { if (window.importscripts) { var ms = (_typeof(urls) === "array") ? urls : [urls]; ms.each(function (url) { window.importscripts(o2.filter); }); var cbk = (_typeof(options) === "function") ? options : callback; if (cbk) cbk(); } } }; /** * @summary 引入外部javascript文件。 * @function load * @memberof o2 * @param {string|array} [urls] 要载入的js文件url,或要载入多个js问价的urls数组。 * @param {object|function} [options|callback] 载入js文件的配置参数,或者载入成功后的回调。 *
options参数格式如下:
         * {
         *      "nocache":  是否使用缓存,默认true,
         *      "reload":   如果相同路径的js文件已经加载了,是否重新载入,默认为:false
         *      "sequence": 当urls参数为数组时,多个脚本文件是否按数组顺序依次载入,默认为false
         *      "type":     载入脚本的类型,默认为"text/javascript"
         *      "baseurl":  要载入脚本的url的base路径,默认""
         *      "doc":      要在哪个document对象中载入脚本文件,默认为当前document
         * }
         * 
* @param {function} [callback] 可选参数,载入成功后的回调方法。 * @o2syntax * o2.load(urls, options, callback); * @example * //载入jsfile1.js和js/jsfile2.js两个文件,它们是按顺序载入的 * o2.load(["js/jsfile1.js", "js/jsfile2.js"], function(){ * //js文件已经载入 * }); * * //载入jsfile1.js和js/jsfile2.js两个文件,它们是同时载入的 * //并且无论是否已经加载过,都需要重新加载,并且要按顺序加载 * o2.load(["js/jsfile1.js", "js/jsfile2.js"], {"reload": true, "sequence": true}, function(){ * //js文件已经载入 * }); */ this.o2.load = _load; //load css var _loadsinglecss = function (module, callback, op, uuid) { var url = module; var uid = _uuid(); if (op.nocache) url = (url.indexof("?") !== -1) ? url "&v=" uid : url "?v=" uid; var key = encodeuricomponent(url op.doc.unid); if (_loadcssrunning[key]) { _loadcssqueue.push(function () { _loadsinglecss(module, callback, op, uuid); }); return; } var completed = function () { if (_loadcssrunning[key]) { _loadcssrunning[key] = false; delete _loadcssrunning[key]; } if (_loadcssqueue && _loadcssqueue.length) { (_loadcssqueue.shift())(); } }; if (_loadedcss[key]) uuid = _loadedcss[key]["class"]; if (op.dom) _parsedom(op.dom, function (node) { if (node.classname.indexof(uuid) == -1) node.classname = ((node.classname) ? " " uuid : uuid); }, op.doc); if (_loadedcss[key]) if (!op.reload) { promise.resolve(_loadedcss[key]).then(function(o){ if (callback) callback(o); }); //if (callback) callback(_loadedcss[key]); completed(); return; } if (op.url){ var style = op.doc.createelement("link"); style.setattribute("rel", "stylesheet"); style.setattribute("type", "text/css"); style.setattribute("id", uuid); style.setattribute("href", url); if (!op.notinject) { var head = (op.doc.head || op.doc.getelementsbytagname("head")[0] || op.doc.documentelement); head.appendchild(style); } var styleobj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid}; if (callback) callback(styleobj); completed(); }else{ var success = function (xhr) { var csstext = xhr.responsetext; try { if (csstext) { op.uuid = uuid; var style = _loadcsstext(csstext, op); } style.id = uid; var styleobj = {"module": module, "id": uid, "style": style, "doc": op.doc, "class": uuid}; _loadedcss[key] = styleobj; if (callback) callback(styleobj); } catch (e) { if (callback) callback(); return; } }; var failure = function (xhr) { console.log("error: load css module: " module); if (callback) callback(); }; _loadcssrunning[key] = true; _xhr_get(url, success, failure, completed); } }; var _parsedomstring = function (dom, fn, sourcedoc) { var doc = sourcedoc || document; var list = doc.queryselectorall(dom); if (list.length) for (var i = 0; i < list.length; i ) _parsedomelement(list[i], fn); }; var _parsedomelement = function (dom, fn) { if (fn) fn(dom); }; var _parsedom = function (dom, fn, sourcedoc) { var domtype = _typeof(dom); if (domtype === "string") _parsedomstring(dom, fn, sourcedoc); if (domtype === "element") _parsedomelement(dom, fn); if (domtype === "array") for (var i = 0; i < dom.length; i ) _parsedom(dom[i], fn, sourcedoc); }; var _loadcss = function (modules, options, callback) { var ms = (_typeof(modules) === "array") ? modules : [modules]; var op = (_typeof(options) === "object") ? _getcssoptions(options) : _getcssoptions(null); var cb = (_typeof(options) === "function") ? options : callback; var uuid = "css" _uuid(); var thisloaded = []; if (op.sequence) { _loadsequence(ms, cb, op, 0, thisloaded, _loadsinglecss, uuid); } else { _loaddisarray(ms, cb, op, thisloaded, _loadsinglecss, uuid); } }; var _removecss = function (modules, doc) { var thisdoc = doc || document; var ms = (_typeof(modules) === "array") ? modules : [modules]; for (var i = 0; i < ms.length; i ) { var module = ms[i]; var k = encodeuricomponent(module (thisdoc.unid || "")); var removecss = _loadedcss[k]; if (!removecss) for (key in _loadedcss) { if (_loadedcss[key].id == module) { removecss = _loadedcss[key]; k = key; break; } } if (removecss) { delete _loadedcss[k]; var stylenode = removecss.doc.getelementbyid(removecss.id); if (stylenode) stylenode.parentnode.removechild(stylenode); removecss = null; } } }; var _loadcsstext = function (csstext, options, callback) { var op = (_typeof(options) === "object") ? _getcssoptions(options) : _getcssoptions(null); var cb = (_typeof(options) === "function") ? options : callback; var uuid = options.uuid || "css" _uuid(); if (csstext) { if (op.dom) _parsedom(op.dom, function (node) { if (node.classname.indexof(uuid) == -1) node.classname = ((node.classname) ? " " uuid : uuid); }, op.doc); csstext = csstext.replace(/\/\*(\s|\s)*?\*\//g, ""); if (op.bind) csstext = csstext.bindjson(op.bind); if (op.dom) { var rex = new regexp("(. )(?=[\\r\\n]*\\{)", "g"); var match; var prefix = "." uuid " "; while ((match = rex.exec(csstext)) !== null) { // var rule = prefix match[0]; // csstext = csstext.substring(0, match.index) rule csstext.substring(rex.lastindex, csstext.length); // rex.lastindex = rex.lastindex prefix.length; var rulesstr = match[0]; var startwith = rulesstr.substring(0, 1); if (startwith === "@" || startwith === ":" || rulesstr.indexof("%") !== -1) { // var begin = 0; // var end = 0; }else if (rulesstr.trim()==='from' || rulesstr.trim()==='to'){ //nothing } else { if (rulesstr.indexof(",") != -1) { //var rules = rulesstr.split(/\s*,\s*/g); var rules = rulesstr.split(/,/g); rules = rules.map(function (r) { return prefix r; }); var rule = rules.join(","); csstext = csstext.substring(0, match.index) rule csstext.substring(rex.lastindex, csstext.length); rex.lastindex = rex.lastindex (prefix.length * rules.length); } else { var rule = prefix match[0]; csstext = csstext.substring(0, match.index) rule csstext.substring(rex.lastindex, csstext.length); rex.lastindex = rex.lastindex prefix.length; } } } } var style = op.doc.createelement("style"); style.setattribute("type", "text/css"); style.setattribute("id", uuid); if (!op.notinject) { var head = (op.doc.head || op.doc.getelementsbytagname("head")[0] || op.doc.documentelement); head.appendchild(style); } if (style.stylesheet) { var setfunc = function () { style.stylesheet.csstext = csstext; }; if (style.stylesheet.disabled) { settimeout(setfunc, 10); } else { setfunc(); } } else { var csstextnode = op.doc.createtextnode(csstext); style.appendchild(csstextnode); } } if (callback) callback(style, uuid); return style; }; /** * @summary 引入外部css资源。 * @function loadcss * @memberof o2 * @param {string|array} [urls] 要载入的css文件url,或要载入多个css文件的urls数组。 * @param {object|function} [options|callback] 载入css文件的配置参数,或者载入成功后的回调。 *
options参数格式如下:
         * {
         *      "nocache":  是否使用缓存,默认true,
         *      "reload":   如果相同路径的css文件已经引入了,是否重新载入,默认为:false
         *      "sequence": 当urls参数为数组时,多个css文件是否按数组顺序依次载入,默认为false
         *      "dom":      dom element对象,表示css在这个element生效,默认是null,表示对整个document生效
         * }
         * 
* @param {function} [callback] 可选参数,载入成功后的回调方法。 * @o2syntax * o2.loadcss(urls, options, callback); * @o2syntax * element.loadcss(urls, options, callback); * @example * //载入style1.css和style2.css两个文件,作用于document * o2.loadcss(["../css/style1.css", "../css/style2.css"], function(){ * //css文件已经载入 * }); * * //载入style1.css和style2.css两个文件,作用于id为content的dom对象 * o2.loadcss(["../css/style1.css", "../css/style2.css"], {"dom": document.getelementbyid("content")}, function(){ * //css文件已经载入 * }); * //在dom对象上载入style1.css和style2.css两个css * var node = document.getelementbyid("mydiv"); * node.loadcss(["../css/style1.css", "../css/style2.css"], function(){ * //css文件已经载入 * }); */ this.o2.loadcss = _loadcss; /** * @summary 引入文本css资源。 * @function loadcsstext * @memberof o2 * @param {string} [csstext] 要载入的css文本内容。 * @param {object|function} [options|callback] 载入css文件的配置参数,或者载入成功后的回调。 *
options参数格式如下:
         * {
         *      "dom":      dom element对象,表示css在这个element生效,默认是null,表示对整个document生效
         * }
         * 
* @param {function} [callback] 可选参数,载入成功后的回调方法。 * @o2syntax * o2.loadcsstext(csstext, options, callback); * @o2syntax * element.loadcsstext(csstext, options, callback); * @see o2.loadcss * @example * //引入css文本,作用于id为content的dom对象 * var csstext = ".myclass{color:#ff0000}" * o2.loadcsstext(csstext, {"dom": document.getelementbyid("content")}, function(){ * //css已经载入 * }); * //引入css文本,作用于id为content的dom对象 * var csstext = ".myclass{color:#ff0000}" * var node = document.getelementbyid("content"); * node.loadcsstext(csstext, function(){ * //css已经载入 * }); */ this.o2.loadcsstext = _loadcsstext; if (window.element) element.prototype.loadcss = function (modules, options, callback) { var op = (_typeof(options) === "object") ? options : {}; var cb = (_typeof(options) === "function") ? options : callback; op.dom = this; _loadcss(modules, op, cb); }; if (window.element) element.prototype.loadcsstext = function (csstext, options, callback) { var op = (_typeof(options) === "object") ? options : {}; var cb = (_typeof(options) === "function") ? options : callback; op.dom = this; return _loadcsstext(csstext, op, cb); }; /** * @summary 移除通过o2.loadcss方法引入css资源。 * @function removecss * @memberof o2 * @param {string|array} [urls] 要移除的的css文本url,必须与引入时所使用的url相同。 * @o2syntax * o2.removecss(urls); * @example * //载入style1.css和style2.css两个文件,作用于id为content的dom对象 * o2.load(["../css/style1.css", "../css/style2.css"], {"dom": document.getelementbyid("content")}, function(){ * //css文件已经载入 * }); * * //移除style1.css和style2.css两个文件 * //引入时使用了"../css/style1.css"字符串作为路径,移除时也要使用相同的字符串 * o2.removecss(["../css/style1.css", "../css/style2.css"]) */ this.o2.removecss = _removecss; //load html _loadsinglehtml = function (module, callback, op) { var url = module; var uid = _uuid(); if (op.nocache) url = (url.indexof("?") !== -1) ? url "&v=" uid : url "?v=" uid; var key = encodeuricomponent(url op.doc.unid); if (!op.reload) if (_loadedhtml[key]) { promise.resolve(_loadedhtml[key]).then(function(html){ if (callback) callback(html); }); //if (callback) callback(_loadedhtml[key]); return; } var success = function (xhr) { var htmlobj = {"module": module, "id": uid, "data": xhr.responsetext, "doc": op.doc}; _loadedhtml[key] = htmlobj; if (callback) callback(htmlobj); }; var failure = function () { console.log("error: load html module: " module); if (callback) callback(); }; _xhr_get(url, success, failure); }; var _injecthtml = function (op, data, baseurl) { if (op.bind) data = data.bindjson(op.bind); if (op.dom) _parsedom(op.dom, function (node) { var scripttext; var scriptsrc; var text = data.stripscriptsrcs(function (script) { scriptsrc = script; }); text = text.stripscripts(function (script) { scripttext = script; }); if (op.baseurl){ var reg = /(?:href|src)\s*=\s*"([^"]*)"/gi; var m = reg.exec(text); while (m) { var l = m[0].length; var u = new uri(m[1], {base: baseurl}).tostring(); var r = m[0].replace(m[1], u); var i = r.length - l; var left = text.substring(0, m.index); var right = text.substring(m.index l, text.length); text = left r right; reg.lastindex = reg.lastindex i; m = reg.exec(text); } } if (op.module) { _parsemodule(node, text, op); //node.insertadjacenthtml(op.position, data); } else { node.insertadjacenthtml(op.position, text); } if (op.evalscripts) { if (scriptsrc) { var scriptsrcs = scriptsrc.split(/\n/g).trim(); if (scriptsrcs && scriptsrcs.length) { o2.load(scriptsrcs, {baseurl: baseurl, reload:true}, function () { }); if (op.evalscripts && scripttext) browser.exec(scripttext); } else { if (op.evalscripts && scripttext) browser.exec(scripttext); } } } }, op.doc); }; var _parsemodule = function (node, data, op) { var dom = op.noconflict ? document.createelement("div") : node; if (op.noconflict) { dom.insertadjacenthtml("afterbegin", data); } else { dom.insertadjacenthtml(op.position, data); } var binddataid = ""; var binddatanode = dom.queryselector("[data-o2-binddata]"); if (binddatanode){ binddataid = binddatanode.dataset["o2binddata"]; binddatanode.destroy(); } var els = dom.queryselectorall("[data-o2-element],[data-o2-events]"); for (var i = 0; i < els.length; i ) { var el = els.item(i); var name = el.getattribute("data-o2-element"); if (name) _bindtomodule(op.module, el, name.tostring()); if (el.hasattribute("data-o2-events")) { var events = el.getattribute("data-o2-events").tostring(); if (events) _bindtoevents(op.module, el, events, binddataid); el.removeattribute("data-o2-events"); } } if (op.noconflict) { var n = dom.firstelementchild; var newnode = node.insertadjacentelement(op.position, n); nextnode = dom.firstelementchild; while (nextnode) { newnode = newnode.insertadjacentelement("afterend", nextnode); nextnode = dom.firstelementchild; } dom.destroy(); } }; var _bindtoevents = function (m, node, events, binddataid) { var p = node.getparent("div[data-o2-binddataid]"); var data = null; if (p){ data = _parsedatacache[p.dataset["o2binddataid"]]; //_parsedatacache[p.dataset["o2binddataid"]] = null; //delete _parsedatacache[p.dataset["o2binddataid"]]; }else{ if (binddataid) data = (_parsedatacache[binddataid] || null); //_parsedatacache[binddataid] = null; //delete _parsedatacache[binddataid]; } // var data = (p) ? _parsedatacache[p.dataset["o2binddataid"]] : (_parsedatacache["bind"] || null); var eventlist = events.split(/\s*;\s*/); eventlist.foreach(function (ev) { var evs = ev.split(/\s*:\s*/); if (evs.length > 1) { var event = evs.shift(); var method = evs.shift(); // if (event==="o2load"){ // // if (m[method]) m[method].apply(m, evs.concat([new pointerevent("o2load"), data])); // }else{ node.addeventlistener(event, function (e) { if (m[method]) m[method].apply(m, evs.concat([e, data])); }, false); // } } }); // try { node.dispatchevent(o2.customeventload); // }catch(e){ // debugger; // console.error(e) // } } var _bindtomodule = function (m, node, name) { // if (m[name]){ // if (o2.typeof(m[name])!=="array"){ // var tmp = m[name]; // m[name] = []; // m[name].push(tmp); // } // m[name].push(node); // }else{ m[name] = node; // } }; var _loadhtml = function (modules, options, callback) { var ms = (_typeof(modules) === "array") ? modules : [modules]; var op = (_typeof(options) === "object") ? _gethtmloptions(options) : _gethtmloptions(null); var cb = (_typeof(options) === "function") ? options : callback; var thisloaded = []; if (op.sequence) { _loadsequence(ms, cb, op, 0, thisloaded, _loadsinglehtml, null, function (html) { if (html) _injecthtml(op, html.data, html.module); }); } else { _loaddisarray(ms, cb, op, thisloaded, _loadsinglehtml, null, function (html) { if (html) _injecthtml(op, html.data, html.module); }); } }; /** * @summary 引入外部html模板资源,并将html内容渲染到指定dom对象的某个位置。 * @function loadhtml * @memberof o2 * @param {string|array} [urls] 要载入的html文件url,或要载入多个html文件的urls数组。 * @param {object|function} [options|callback] 载入html文件的配置参数,或者载入成功后的回调。 *
options参数格式如下:
         * {
         *       "nocache":  是否使用缓存,默认true,
         *       "reload":   如果相同路径的html文件已经引入了,是否重新载入,默认为:false
         *       "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
         *       "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
         *       "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
         *       "module": object,与此html模板关联的对象。(在下面的例子中详细介绍)
         *       "bind": json,与此html模板关联的json对象。(在下面的例子中详细介绍)
         *       "evalscripts": html模板中通过<script>引入或内嵌的javascript,是否要执行。默认为false
         *       "baseurl": html模板中引用连接的baseurl,默认为空
         * }
         * 
* @param {function} [callback] 可选参数,载入成功后的回调方法。 * @o2syntax * o2.loadhtml(urls, options, callback); * @o2syntax * element.loadhtml(urls, options, callback); * @example * 样例1: 引入一个html模板文件,并插入到id为content的dom对象的最后 * //引入一个html模板文件,并插入到id为content的dom对象的最后 * var node = document.getelementbyid("content"); * o2.loadhtml("../html/template.html", {"dom": node}, function(){ * //html文件已经载入 * }); * * //或者使用element.loadhtml方法 * var node = document.getelementbyid("content"); * node.loadhtml("../html/template.html", function(){ * //html文件已经载入 * }); * * @example * * 样例2: 本例中我们使用一个html模板来渲染展现已有的数据。我们将一个json对象绑定到要载入的模板,通过{{$.xxx}}来展现json数据。
* html模板内容如下: *
<div>{{$.title}}</div>
         * <div>{{$.description}}</div>
* 然后通过以下代码来载入html模板: * * var json = { * "title": "这是标题", * "description": "描述内容" * }; * var node = document.getelementbyid("content"); * o2.loadhtml("../html/template.html", {"dom": node, "bind": json}, function(){ * //html文件已经载入 * //载入后,node对象的html如下: * //
* // ...... * //
这是标题
; * //
描述内容
* //
* }); * @example * * 样例3: 本例中我们除了使用一个html模板来渲染展现已有的json数据,还给已有模块绑定上html模板中的一个dom对象,并监听html模板中的指定元素的事件。
* html模板内容如下: *
<div>{{$.title}}</div>
         * <div>{{$.description}}</div>
         * <div data-o2-element="myelement"></div>
         * <button data-o2-events="click:clickme:{{$.info}};mouseover:overme;mouseout:outme">绑定了事件的按钮</button>
         * 
* 然后通过以下代码来载入html模板: * * //json数据 * var json = { * "title": "这是标题", * "description": "描述内容", * "info": "按钮点击后的信息" * }; * //业务模块 * var module = { * //当button按钮被点击时,会调用此方法 * clickme: function(info, e){ * this.myelement.insertadjacenttext("afterbegin", "button clicked " info); * }, * //当鼠标移动到button按钮时,会调用此方法 * overme: function(e){ * console.log("button over"); * console.log(e); //mouseevent对象 * }, * //当鼠标移出button按钮时,会调用此方法 * outme: function(e){ * console.log("button out"); * console.log(e); //mouseevent对象 * } * }; * * var node = document.getelementbyid("content"); * node.loadhtml("../html/template.html", {"bind": json, "module": module}, function(){ * //html文件已经载入 * //载入后,node对象的html如下: * //
* // ...... * //
这是标题
; * //
描述内容
* //
* // * //
* console.log(module.myelement); //dom对象:
* //html模板中的div对象,被绑定到了module对象的myelement属性上 * * }); * @example * * 样例4: 本例中演示了html模板中each和if的用法。
* html模板内容如下: *
<div>
         *    {{each $.items}}
         *        <div>{{$.title}}</div>
         *        <div>{{$.description}}</div>
         *        {{if $.title=="这是标题2"}}
         *             <div>这是标题2的个性化内容</div>
         *        {{end if}}
         *        <button data-o2-events="click:clickme:{{$.info}}">绑定了事件的按钮</button>
         *        <hr>
         *    {{end each}}
         * </div>
* 然后通过以下代码来载入html模板: * * //json数据 * var json = { * "items": [{ * "title": "这是标题1", * "description": "描述内容1", * "info": "按钮点击后的信息1" * },{ * "title": "这是标题2", * "description": "描述内容2", * "info": "按钮点击后的信息2" * },{ * "title": "这是标题3", * "description": "描述内容3", * "info": "按钮点击后的信息3" * }] * }; * //业务模块 * var module = { * //当button按钮被点击时,会调用此方法 * clickme: function(info, e){ * alert(info); * } * }; * var node = document.getelementbyid("content"); * node.loadhtml("../html/template.html", {"bind": json, "module": module}, function(){ * //html文件已经载入 * //载入后,node对象的html如下: * //
* //
这是标题1
; * //
描述内容1
* // * //
* //
* //
* //
这是标题2
; * //
描述内容2
* //
描这是标题2的个性化内容
* // * //
* //
* //
* //
这是标题3
; * //
描述内容3
* // * //
* //
* //当点击按钮时,会alert对应的items的info数据 * }); */ this.o2.loadhtml = _loadhtml; if (window.element) element.prototype.loadhtml = function (modules, options, callback) { var op = (_typeof(options) === "object") ? options : {}; var cb = (_typeof(options) === "function") ? options : callback; op.dom = this; _loadhtml(modules, op, cb); }; /** * @summary 解析html文本内容,并将html内容渲染到指定dom对象的某个位置,与loadhtml相同,只是传入html内容,而不是获取html的url。 * @function loadhtmltext * @memberof o2 * @param {string} [html] 要解析的html文本内容。 * @param {object} [options] 载入html文件的配置参数。 *
options参数格式如下:
         * {
         *       "nocache":  是否使用缓存,默认true,
         *       "reload":   如果相同路径的html文件已经引入了,是否重新载入,默认为:false
         *       "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
         *       "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
         *       "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
         *       "module": object,与此html模板关联的对象。(在下面的例子中详细介绍)
         *       "bind": json,与此html模板关联的json对象。(在下面的例子中详细介绍)
         *       "evalscripts": html模板中通过<script>引入或内嵌的javascript,是否要执行。默认为false
         *       "baseurl": html模板中引用连接的baseurl,默认为空
         * }
         * 
* @o2syntax * o2.loadhtmltext(html, options); * @o2syntax * element.loadhtmltext(html, options); * @see o2.loadhtml * @example * var html = "
{{$.title}}
" * var json = {"title": "标题"}; * var node = document.getelementbyid("content"); * o2.loadhtmltext(html, {"dom": node, "bind": json}); * * //获 * node.loadhtmltext(html, {"bind": json}); */ this.o2.loadhtmltext = this.o2.injecthtml = function (html, options) { var op = (_typeof(options) === "object") ? _gethtmloptions(options) : _gethtmloptions(null); _injecthtml(op, html); }; if (window.element) element.prototype.loadhtmltext = element.prototype.injecthtml = function (html, options) { var op = (_typeof(options) === "object") ? options : {}; op.dom = this; op.position = (options && options.position) || "beforeend" _injecthtml(op, html); }; //load all _loadall = function (modules, options, callback) { //var ms = (_typeof(modules)==="array") ? modules : [modules]; var op = (_typeof(options) === "object") ? _getalloptions(options) : _getalloptions(null); var cb = (_typeof(options) === "function") ? options : callback; var ms, htmls, styles, sctipts; var _htmlloaded = (!modules.html), _cssloaded = (!modules.css), _jsloaded = (!modules.js); var _checkloaded = function () { if (_htmlloaded && _cssloaded && _jsloaded) if (cb) cb(htmls, styles, sctipts); }; if (modules.html) { _loadhtml(modules.html, op, function (h) { htmls = h; _htmlloaded = true; _checkloaded(); }); } if (modules.css) { _loadcss(modules.css, op, function (s) { styles = s; _cssloaded = true; _checkloaded(); }); } if (modules.js) { _load(modules.js, op, function (s) { sctipts = s; _jsloaded = true; _checkloaded(); }); } }; /** * @summary 同时载入js文件、css文件和html模板文件,相当于同时调用了o2.load, o2.loadcss 和 o2.loadhtml。 * @function loadall * @memberof o2 * @param {object} [modules] 要解析的html文本内容。 *
modules参数格式如下:
         * {
         *       "js": {string|array} 要载入的js文件url,或要载入多个js文件的urls数组。
         *       "css": {string|array} 要载入的css文件url,或要载入多个css文件的urls数组。
         *       "html": {string|array} 要载入的html文件url,或要载入多个html文件的urls数组。
         * }
         * 
* @param {object} [options] 载入html文件的配置参数。 *
options参数格式如下:
         * {
         *       "nocache":  是否使用缓存,默认true,
         *       "reload":   如果相同路径的html文件已经引入了,是否重新载入,默认为:false
         *       "sequence": 当urls参数为数组时,多个html文件是否按数组顺序依次载入,默认为false
         *       "dom": 引入html后,要将html内容渲染到的目标dom对象(具体位置由position参数确定),
         *       "position": 渲染到的目标dom对象的位置,可以是以下值:'beforebegin' 'afterbegin' 'beforeend'(默认) 'afterend'
         *       "module": object,与此html模板关联的对象。(在下面的例子中详细介绍)
         *       "bind": json,与此html模板关联的json对象。(在下面的例子中详细介绍)
         *       "evalscripts": html模板中通过<script>引入或内嵌的javascript,是否要执行。默认为false
         *       "baseurl": html模板中引用连接的baseurl,默认为空
         * }
         * 
* @param {function} [callback] 可选参数,载入成功后的回调方法。 * @o2syntax * o2.loadall(modules, options, callback); * @o2syntax * element.loadall(modules, options, callback); * @see o2.load * @see o2.loadcss * @see o2.loadhtml * @example * var html = "
{{$.title}}
" * var json = {"title": "标题"}; * var node = document.getelementbyid("content"); * o2.loadall({ * "js": ["file1.js", "file2.js"], * "css": ["style.css"], * "html": "template.html", * }, {"dom": node, "bind": json}, function(){ * //载入完成后的回调 * }); */ this.o2.loadall = _loadall; if (window.element) element.prototype.loadall = function (modules, options, callback) { var op = (_typeof(options) === "object") ? options : {}; var cb = (_typeof(options) === "function") ? options : callback; op.dom = this; _loadall(modules, op, cb); }; var _getifblockend = function (v) { var rex = /(\{\{if\s )|(\{\{\s*end if\s*\}\})/gmi; var rexend = /\{\{\s*end if\s*\}\}/gmi; var subs = 1; while ((match = rex.exec(v)) !== null) { var fullmatch = match[0]; if (fullmatch.search(rexend) !== -1) { subs--; if (subs == 0) break; } else { subs } } if (match) return {"codeindex": match.index, "lastindex": rex.lastindex}; return {"codeindex": v.length - 1, "lastindex": v.length - 1}; } var _geteachblockend = function (v) { var rex = /(\{\{each\s )|(\{\{\s*end each\s*\}\})/gmi; var rexend = /\{\{\s*end each\s*\}\}/gmi; var subs = 1; while ((match = rex.exec(v)) !== null) { var fullmatch = match[0]; if (fullmatch.search(rexend) !== -1) { subs--; if (subs == 0) break; } else { subs ; } } if (match) return {"codeindex": match.index, "lastindex": rex.lastindex}; return {"codeindex": v.length - 1, "lastindex": v.length - 1}; } var _parsedatacache = {}; var _parsehtml = function (str, json, i) { var v = str; var r = (math.random() * 1000000).toint().tostring(); while (_parsedatacache[r]) r = (math.random() * 1000000).toint().tostring(); if (i || i===0) { _parsedatacache[r] = json; v = "
" str "
"; }else{ var regex = new regexp("\\<[\\s\\s] \\>"); if (regex.test(str)){ if (json.data){ _parsedatacache[r] = json.data; v = str "
" } } } var rex = /(\{\{\s*)[\s\s]*?(\s*\}\})/gmi; var match; while ((match = rex.exec(v)) !== null) { var fullmatch = match[0]; var offset = 0; //if statement begin if (fullmatch.search(/\{\{if\s /i) !== -1) { //找到对应的end if var condition = fullmatch.replace(/^\{\{if\s*/i, ""); condition = condition.replace(/\s*\}\}$/i, ""); var flag = _jsontext(json, condition, "boolean"); var tmpstr = v.substring(rex.lastindex, v.length); var endifindex = _getifblockend(tmpstr); if (flag) { //if 为 true var parsestr = _parsehtml(tmpstr.substring(0, endifindex.codeindex), json); var vleft = v.substring(0, match.index); var vright = v.substring(rex.lastindex endifindex.lastindex, v.length); v = vleft parsestr vright; offset = parsestr.length - fullmatch.length; } else { v = v.substring(0, match.index) v.substring(rex.lastindex endifindex.lastindex, v.length); offset = 0 - fullmatch.length; } } else if (fullmatch.search(/\{\{each\s /) !== -1) { //each statement var itemstring = fullmatch.replace(/^\{\{each\s*/, ""); itemstring = itemstring.replace(/\s*\}\}$/, ""); var eachvalue = _jsontext(json, itemstring, "object"); var tmpeachstr = v.substring(rex.lastindex, v.length); var endeachindex = _geteachblockend(tmpeachstr); var parseeachstr = tmpeachstr.substring(0, endeachindex.codeindex); var eachresult = ""; if (eachvalue && _typeof(eachvalue) === "array") { for (var i = 0; i < eachvalue.length; i ) { eachvalue[i]._ = json; eachresult = _parsehtml(parseeachstr, eachvalue[i], i); } var eleft = v.substring(0, match.index); var eright = v.substring(rex.lastindex endeachindex.lastindex, v.length); v = eleft eachresult eright; offset = eachresult.length - fullmatch.length; } else { v = v.substring(0, match.index) v.substring(rex.lastindex endeachindex.lastindex, v.length); offset = 0 - fullmatch.length; } } else { //text statement var text = fullmatch.replace(/^\{\{\s*/, ""); text = text.replace(/\}\}\s*$/, ""); var value = _jsontext(json, text); offset = value.length - fullmatch.length; v = v.substring(0, match.index) value v.substring(rex.lastindex, v.length); } rex.lastindex = rex.lastindex offset; } return v; }; var _jsontext = function (json, text, type) { try { var $ = json; var f = eval("(function($){\n return " text ";\n})"); returnvalue = f.apply(json, [$]); if (returnvalue === undefined) returnvalue = ""; if (type === "boolean") return (!!returnvalue); if (type === "object") return returnvalue; returnvalue = returnvalue.tostring(); returnvalue = returnvalue.replace(/\&/g, "&"); returnvalue = returnvalue.replace(/>/g, ">"); returnvalue = returnvalue.replace(/. * * ***** end license block ******/ (function () { var _class = { create: function (options) { // var newclass = function() { // this.initialize.apply(this, arguments); // }; return _copyprototype(function () { return this.initialize.apply(this, arguments) || this; }, options); //return newclass; } }; var _copyprototype = function (currentns, props) { if (!props) { return currentns; } if (!currentns) { return currentns; } if ((typeof currentns).tolowercase() === "object") { for (var prop in props) { currentns[prop] = props[prop]; } } if ((typeof currentns).tolowercase() === "function") { for (var propfun in props) { currentns.prototype[propfun] = props[propfun]; } } return currentns; }; var _loaded = {}; var _requirejs = function (url, callback, async, compression, module) { var key = encodeuricomponent(url); if (_loaded[key]) { o2.runcallback(callback, "success", [module]); return ""; } var jspath = (compression || !this.o2.session.isdebugger) ? url.replace(/\.js/, ".min.js") : url; jspath = (jspath.indexof("?") !== -1) ? jspath "&v=" this.o2.version.v : jspath "?v=" this.o2.version.v; if (window.importscripts) { window.importscripts(o2.filter); o2.runcallback(callback, "success", [module]); } else { var xhr = new request({ url: o2.filter, async: async, method: "get", onsuccess: function () { //try{ _loaded[key] = true; o2.runcallback(callback, "success", [module]); //}catch (e){ // o2.runcallback(callback, "failure", [e]); //} }, onfailure: function (r) { var rex = /lp\/. \.js/; if (rex.test(url)) { var zhcnurl = url.replace(rex, "lp/zh-cn.js"); if (zhcnurl !== url) { _requirejs(zhcnurl, callback, async, compression, module) } else { o2.runcallback(callback, "failure", [r]); } } else { o2.runcallback(callback, "failure", [r]); } } }); xhr.send(); } }; var _requiresingle = function (module, callback, async, compression) { if (o2.typeof(module) === "array") { _requireappsingle(module, callback, async, compression); } else { module = module.replace("mwf.", "o2."); var levels = module.split("."); if (levels[levels.length - 1] === "*") levels[levels.length - 1] = "package"; levels.shift(); var o = o2; var i = 0; while (o && i < levels.length) { o = o[levels[i]]; i } if (!o) { var jspath = this.o2.session.path; jspath = "/" levels.join("/") ".js"; var loadasync = (async !== false); _requirejs(jspath, callback, loadasync, compression, module); } else { o2.runcallback(callback, "success", [module]); } } }; var _requiresequence = function (fun, module, thisloaded, thiserrorloaded, callback, async, compression) { var m = module.shift(); fun(m, { "onsuccess": function (m) { thisloaded.push(m); o2.runcallback(callback, "every", [m]); if (module.length) { _requiresequence(fun, module, thisloaded, thiserrorloaded, callback, async, compression); } else { if (thiserrorloaded.length) { o2.runcallback(callback, "failure", [thisloaded, thiserrorloaded]); } else { o2.runcallback(callback, "success", [thisloaded, thiserrorloaded]); } } }, "onfailure": function () { thiserrorloaded.push(module[i]); o2.runcallback(callback, "failure", [thisloaded, thiserrorloaded]); } }, async, compression); }; var _requiredisarray = function (fun, module, thisloaded, thiserrorloaded, callback, async, compression) { for (var i = 0; i < module.length; i ) { fun(module[i], { "onsuccess": function (m) { thisloaded.push(m); o2.runcallback(callback, "every", [m]); if ((thisloaded.length thiserrorloaded.length) === module.length) { if (thiserrorloaded.length) { o2.runcallback(callback, "failure", [thisloaded, thiserrorloaded]); } else { o2.runcallback(callback, "success", [thisloaded, thiserrorloaded]); } } }, "onfailure": function () { thiserrorloaded.push(module[i]); o2.runcallback(callback, "failure", [thisloaded, thiserrorloaded]); } }, async, compression); } }; var _require = function (module, callback, async, sequence, compression) { var type = typeof(module); if (type === "array") { var sql = !!sequence; var thisloaded = []; var thiserrorloaded = []; if (sql) { _requiresequence(_requiresingle, module, thisloaded, thiserrorloaded, callback, async, compression); } else { _requiredisarray(_requiresingle, module, thisloaded, thiserrorloaded, callback, async, compression); } } if (type === "string") { _requiresingle(module, callback, async, compression); } }; var _requireappsingle = function (modules, callback, async, compression) { var module = modules[0]; var clazz = modules[1]; var levels = module.split("."); var o = o2.xapplication; var i = 0; while (o && i < levels.length) { o = o[levels[i]]; i } if (o) o = o[clazz || "main"]; if (!o) { //levels.shift(); var root = "x_component_" levels.join("_"); var clazzname = clazz || "main"; var path = "../" root "/" clazzname.replace(/\./g, "/") ".js"; var loadasync = (async !== false); _requirejs(path, callback, loadasync, compression); } else { o2.runcallback(callback, "success"); } }; var _requireapp = function (module, clazz, callback, async, sequence, compression) { var type = typeof(module); if (type === "array") { var sql = !!sequence; var thisloaded = []; var thiserrorloaded = []; if (sql) { _requiresequence(_requireappsingle, module, thisloaded, thiserrorloaded, callback, async, compression); } else { _requiredisarray(_requireappsingle, module, thisloaded, thiserrorloaded, callback, async, compression); } } if (type === "string") { var modules = [module, clazz]; _requireappsingle(modules, callback, async, compression); } }; json = window.json || {}; var _json = json; _json.get = function (url, callback, async, nocache) { var loadasync = (async !== false); var nojsoncache = (nocache === true); if (url.indexof("config.json") > -1){ nojsoncache = true; } url = (url.indexof("?") !== -1) ? url "&v=" o2.version.v : url "?v=" o2.version.v; var json = null; var res = new request.json({ url: o2.filter, secure: false, method: "get", nocache: nojsoncache, async: loadasync, withcredentials: true, onsuccess: function (responsejson, responsetext) { json = responsejson; if (typeof(callback).tolowercase() === 'function') { callback(responsejson, responsetext); } else { o2.runcallback(callback, "success", [responsejson, responsetext]); } }.bind(this), onfailure: function (xhr) { o2.runcallback(callback, "requestfailure", [xhr]); }.bind(this), onerror: function (text, error) { o2.runcallback(callback, "error", [text, error]); }.bind(this) }); res.send(); return json; }; _json.getjsonp = function (url, callback, async, callbackkey) { var loadasync = (async !== false); var callbackkeyword = callbackkey || "callback"; url = (url.indexof("?") !== -1) ? url "&v=" o2.version.v : url "?v=" o2.version.v; var res = new request.jsonp({ url: o2.filter, secure: false, method: "get", nocache: true, async: loadasync, callbackkey: callbackkeyword, onsuccess: function (responsejson, responsetext) { o2.runcallback(callback, "success", [responsejson, responsetext]); }.bind(this), onfailure: function (xhr) { o2.runcallback(callback, "requestfailure", [xhr]); }.bind(this), onerror: function (text, error) { o2.runcallback(callback, "error", [text, error]); }.bind(this) }); res.send(); }; var _loadlp = function (name) { var jspath = o2.session.path; jspath = jspath "/lp/" name ".js"; var r = new request({ url: o2.filter, async: false, method: "get", onsuccess: function (responsetext) { try { browser.exec(responsetext); } catch (e) { } }, onfailure: function (xhr) { if (name != "zh-cn") { _loadlp("zh-cn"); } else { throw "loadlp error: " xhr.responsetext; } } }); r.send(); }; var _cacheurls = (browser.name == "ie") ? [] : [ /jaxrs\/form\/workorworkcompleted\/. /ig, /jaxrs\/form\/. /ig, /jaxrs\/script\/. \/app\/. \/imported/ig, /jaxrs\/script\/portal\/. \/name\/. \/imported/ig, /jaxrs\/script\/. \/application\/. \/imported/ig, /jaxrs\/page\/. \/portal\/. /ig, /jaxrs\/document\/. /ig, /jaxrs\/applicationdict\/. /ig, /jaxrs\/custom\/. /ig, /jaxrs\/definition\/idea. /ig, /jaxrs\/distribute\/assemble\/source\/. /ig, ]; // _restful_bak = function(method, address, data, callback, async, withcredentials, cache){ // var loadasync = (async !== false); // var credentials = (withcredentials !== false); // address = (address.indexof("?")!==-1) ? address "&v=" o2.version.v : address "?v=" o2.version.v; // //var nocache = cache===false; // var nocache = !cache; // // // //if (browser.name == "ie") // if (_cacheurls.length){ // for (var i=0; i<_cacheurls.length; i ){ // _cacheurls[i].lastindex = 0; // if (_cacheurls[i].test(address)){ // nocache = false; // break; // } // } // } // //var nocache = false; // var res = new request.json({ // url: o2.filter, // secure: false, // method: method, // emulation: false, // nocache: nocache, // async: loadasync, // withcredentials: credentials, // onsuccess: function(responsejson, responsetext){ // // var xtoken = this.getheader("authorization"); // // if (!xtoken) xtoken = this.getheader("x-token"); // var xtoken = this.getheader("x-token"); // if (xtoken){ // if (window.layout){ // if (!layout.session) layout.session = {}; // layout.session.token = xtoken; // } // } // o2.runcallback(callback, "success", [responsejson]); // }, // onfailure: function(xhr){ // o2.runcallback(callback, "requestfailure", [xhr]); // }.bind(this), // onerror: function(text, error){ // o2.runcallback(callback, "error", [text, error]); // }.bind(this) // }); // // res.setheader("content-type", "application/json; charset=utf-8"); // res.setheader("accept", "text/html,application/json,*/*"); // if (window.layout) { // if (layout["debugger"]){ // res.setheader("x-debugger", "true"); // } // if (layout.session && layout.session.user){ // if (layout.session.user.token) { // res.setheader("x-token", layout.session.user.token); // res.setheader("authorization", layout.session.user.token); // } // } // } // //content-type application/x-www-form-urlencoded; charset=utf-8 // res.send(data); // return res; // }; var _resgetqueue = {}; var _checkrestful = function(address, callback){ if (_resgetqueue[address]){ var respromise = _resgetqueue[address]; var p = new promise(function(resolve, reject){ respromise.then(function(){ resolve(respromise.json); }, function(){ reject(respromise.err); }); }); if (_resgetqueue[address].res) p.res = _resgetqueue[address].res; if (_resgetqueue[address].actionworker) p.actionworker = _resgetqueue[address].actionworker; return p; } return false } _restful = function (method, address, data, callback, async, withcredentials, cache) { var p = null; if (method.tolowercase()==="get" && async!==false){ p = _checkrestful(address, callback); //if (p) return p; } var _addr = address; var loadasync = (async !== false); var credentials = (withcredentials !== false); address = (address.indexof("?") !== -1) ? address "&v=" o2.version.v : address "?v=" o2.version.v; //var nocache = cache===false; var nocache = !cache; //if (browser.name == "ie") if (_cacheurls.length) { for (var i = 0; i < _cacheurls.length; i ) { _cacheurls[i].lastindex = 0; if (_cacheurls[i].test(address)) { nocache = false; break; } } } var usewebworker = (window.layout && layout.config && layout.config.usewebworker); //var nocache = false; if (!loadasync || !usewebworker) { var res; if (!p) p = new promise(function (resolve, reject) { res = new request.json({ url: o2.filter, secure: false, method: method, emulation: false, nocache: nocache, async: loadasync, withcredentials: credentials, onsuccess: function (responsejson, responsetext) { // var xtoken = this.getheader("authorization"); // if (!xtoken) xtoken = this.getheader("x-token"); _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; var xtoken = this.getheader(o2.tokenname); if (xtoken) { if (window.layout) { if (!layout.session) layout.session = {}; layout.session.token = xtoken; } if (layout.config && layout.config.sessionstorageenable && window.sessionstorage) window.sessionstorage.setitem("o2layoutsessiontoken", xtoken); } if (!loadasync){ var r = o2.runcallback(callback, "success", [responsejson], null); resolve(r || responsejson); }else{ resolve(responsejson); } //resolve(responsejson); //return o2.runcallback(callback, "success", [responsejson],null, resolve); }, onfailure: function (xhr) { _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; if (!loadasync){ var r = o2.runcallback(callback, "failure", [xhr, "", ""], null); reject((r) ? r : {"xhr": xhr, "text": "", "error": "error"}); }else{ reject({"xhr": xhr, "text": "", "error": "error"}); } }.bind(this), onerror: function (text, error) { _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; if (!loadasync){ var r = o2.runcallback(callback, "failure", [text, error], null); reject((r) ? r : {"xhr": xhr, "text": text, "error": "error"}); }else{ reject({"xhr": xhr, "text": text, "error": "error"}); } }.bind(this), oncomplete: function(){ _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; }, oncancel: function(){ _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; } }); res.setheader("content-type", "application/json; charset=utf-8"); res.setheader("accept", "text/html,application/json,*/*"); res.setheader("accept-language", o2.languagename); if (window.layout) { if (layout["debugger"]) { res.setheader("x-debugger", "true"); } var token = (layout.config && layout.config.sessionstorageenable && window.sessionstorage) ? window.sessionstorage.getitem("o2layoutsessiontoken") : ""; if (!token) { if (layout.session && (layout.session.user || layout.session.token)) { token = layout.session.token; if (!token && layout.session.user && layout.session.user.token) token = layout.session.user.token; } } if (token) { //res.setheader(o2.tokenname, token); res.setheader("authorization", token); } } res.send(data); }.bind(this)).catch(function (err) { throw err; }); // .then(function (responsejson) { // // _resgetqueue[address].events.each(function(e){ // var r = o2.runcallback(e.callback, "success", [responsejson], null); // if (e.promise){ // e.promise // } // }); // // return responsejson; // }, function(err){ // var r = o2.runcallback(callback, "failure", [xhr, "", ""], null); // return r || err; // }).catch(function (err) { // throw err; // //return promise.reject(err); // }); var oreturn = p; //oreturn.res = res; var respromise = promise.resolve(oreturn).then(function(json){ if (!loadasync) return json; respromise.json = json; var r = o2.runcallback(callback, "success", [json], null); if (r) return r; }, function(err){ if (!loadasync) return err; respromise.err = err; var r = o2.runcallback(callback, "failure", [err.xhr, err.text, err.error], null); if (r) return promise.reject(r); return promise.reject(err); }).catch(function (err) { throw err;}); respromise.res = res; if (loadasync) _resgetqueue[_addr] = respromise; return respromise; } else { var workermessage = { method: method, nocache: nocache, loadasync: loadasync, credentials: credentials, address: o2.filter, body: data, debug: (window.layout && layout["debugger"]), token: (window.layout && layout.session && layout.session.user) ? layout.session.user.token : "", tokenname: o2.tokenname } var actionworker = new worker("../o2_core/o2/actionworker.js"); if (!p) p = new promise(function (s, f) { actionworker.onmessage = function (e) { _resgetqueue[_addr] = null; delete _resgetqueue[_addr]; result = e.data; if (result.type === "done") { var xtoken = result.data.xtoken; if (xtoken) { if (window.layout) { if (!layout.session) layout.session = {}; layout.session.token = xtoken; } } s(result.data); //o2.runcallback(callback, "success", [result.data], null, s); } else { f(result.data); //o2.runcallback(callback, "failure", [result.data], null, f); } actionworker.terminate(); } actionworker.postmessage(workermessage); }.bind(this)); // p = p.then(function (data) { // return o2.runcallback(callback, "success", [data], null); // }, function (data) { // return o2.runcallback(callback, "failure", [data], null); // }); //var oreturn = (callback.success && callback.success.addresolve) ? callback.success : callback; var oreturn = p; //oreturn.actionworker = actionworker; var respromise = promise.resolve(oreturn).then(function(json){ respromise.json = json; var r = o2.runcallback(callback, "success", [json], null); if (r) return r; }, function(err){ respromise.err = err; var r = o2.runcallback(callback, "failure", [err], null); if (r) return r; }).catch(function (err) { throw err;}); respromise.actionworker = actionworker; _resgetqueue[_addr] = respromise; return respromise; //return oreturn; //return callback; } //return res; }; var _release = function (o) { var type = typeof(o); switch (type) { case "object": for (var k in o) { //if (o[k] && o[k].destroy) o[k].destroy(); o[k] = null; } break; case "array": for (var i = 0; i < o.length; i ) { _release(o[i]); if (o[i]) o[i] = null; } break; } }; var _defineproperties = object.defineproperties || function (obj, properties) { function converttodescriptor(desc) { function hasproperty(obj, prop) { return object.prototype.hasownproperty.call(obj, prop); } function iscallable(v) { // nb: modify as necessary if other values than functions are callable. return typeof v === "function"; } if (typeof desc !== "object" || desc === null) throw new typeerror("bad desc"); var d = {}; if (hasproperty(desc, "enumerable")) d.enumerable = !!desc.enumerable; if (hasproperty(desc, "configurable")) d.configurable = !!desc.configurable; if (hasproperty(desc, "value")) d.value = desc.value; if (hasproperty(desc, "writable")) d.writable = !!desc.writable; if (hasproperty(desc, "get")) { var g = desc.get; if (!iscallable(g) && typeof g !== "undefined") throw new typeerror("bad get"); d.get = g; } if (hasproperty(desc, "set")) { var s = desc.set; if (!iscallable(s) && typeof s !== "undefined") throw new typeerror("bad set"); d.set = s; } if (("get" in d || "set" in d) && ("value" in d || "writable" in d)) throw new typeerror("identity-confused descriptor"); return d; } if (typeof obj !== "object" || obj === null) throw new typeerror("bad obj"); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var j = 0; j < keys.length; j ) descs.push([keys[j], converttodescriptor(properties[keys[j]])]); for (var i = 0; i < descs.length; i ) { if (object.defineproperty && (browser.name == "ie" && browser.version != 8)) { object.defineproperty(obj, descs[i][0], descs[i][1]); } else { if (descs[i][1].value) obj[descs[i][0]] = descs[i][1].value; if (descs[i][1].get) obj["get" descs[i][0].capitalize()] = descs[i][1].get; if (descs[i][1].set) obj["set" descs[i][0].capitalize()] = descs[i][1].set; } } return obj; }; if (!array.prototype.findindex) { object.defineproperty(array.prototype, 'findindex', { value: function (predicate) { if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); var len = o.length >>> 0; if (typeof predicate !== 'function') { throw new typeerror('predicate must be a function'); } var thisarg = arguments[1]; var k = 0; while (k < len) { var kvalue = o[k]; if (predicate.call(thisarg, kvalue, k, o)) { return k; } k ; } return -1; } }); } if (!array.prototype.find) { object.defineproperty(array.prototype, 'find', { value: function (predicate) { if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); var len = o.length >>> 0; if (typeof predicate !== 'function') { throw new typeerror('predicate must be a function'); } var thisarg = arguments[1]; var k = 0; while (k < len) { var kvalue = o[k]; if (predicate.call(thisarg, kvalue, k, o)) { return kvalue; } k ; } return undefined; } }); } var _txt = function (v) { if (typeof v !== "string") return v; var t = v.replace(/\/g, ">"); return t; }; var _dtxt = function (v) { if (typeof v !== "string") return v; var t = v.replace(/</g, "<"); t = t.replace(/>/g, ">"); return t; }; this.o2.class = _class; this.o2.require = _require; this.o2.requireapp = _requireapp; this.o2.json = _json; this.o2.loadlp = _loadlp; this.o2.restful = _restful; this.o2.release = _release; this.o2.defineproperties = _defineproperties; this.o2.txt = _txt; this.o2.dtxt = _dtxt; object.repeatarray = function (o, count) { var arr = []; for (var i = 0; i < count; i ) { arr.push(o) } return arr; } /** * @summary 从服务器获取当前时间。 * @function getdatefromserver * @memberof o2 * @param {boolean|function} [async|callback] 可选,如果传入true或一个function:表示异步调用此方法,传入的function为回调方法。如果省略此参数或传入false,则为同步方法 * @return {date|promise} 同步调用时,返回获取到的时间date;异步调用时,返回promise。 * @o2syntax * o2.getdatefromserver(async); * @o2syntax * date.getfromserver(async); * @example * //同步获取服务器时间 * var d = o2.getdatefromserver(); * //或者 * var d = date.getfromserver(); * * //通过回调方法异步获取服务器时间 * o2.getdatefromserver(function(d){ * console.log(d); //从服务器获取的当前时间 * }); * //或者 * date.getfromserver(function(d){ * console.log(d); //从服务器获取的当前时间 * }); * * //通过promise异步获取服务器时间 * o2.getdatefromserver(true).then((d)=>{ * console.log(d); //从服务器获取的当前时间 * }); * //或者 * date.getfromserver(true).then((d)=>{ * console.log(d); //从服务器获取的当前时间 * }); */ this.o2.getdatefromserver = date.getfromserver = function (async) { var d; // var cb = ((async && o2.typeof(async) == "function") ? async : null) || function (json) { // //var cb = function(json){ // d = date.parse(json.data.servertime); // return d; // }; var cb = function(json){ d = date.parse(json.data.servertime); return d; } var promise = o2.actions.get("x_program_center").echo(cb, null, !!async); if (async && o2.typeof(async) == "function"){ return promise.then(async); } return (!!async) ? promise : d; }; var _promiseall = function (p) { if (o2.typeof(p) == "array") { if (p.some(function (e) { return (e && o2.typeof(e.then) == "function") })) { return promise.all(p); } else { return { "then": function (s) { if (s) { var r = s(p); return (r && r.then && o2.typeof(r.then) == "function") ? r : this; } return this; } }; } } else { if (p && o2.typeof(p.then) == "function") { return promise.resolve(p); } else { return { "then": function (s) { if (s) { var r = s(p); return (r && r.then && o2.typeof(r.then) == "function") ? r : this; } return this; } }; //return new promise(function(s){s(p); return this;}); } } // var method = (o2.typeof(p)=="array") ? "all" : "resolve"; // return promise[method](p); } o2.promiseall = _promiseall; })(); o2.defer = function(fn, timer, bind, pars){ if (fn.timerid) cleartimeout(fn.timerid); fn.timerid = settimeout(function(){ fn.timerid = null; fn.apply((bind || this), pars); }, timer); } o2.core = true; /** ***** begin license block ***** * |------------------------------------------------------------------------------| * | o2oa 活力办公 创意无限 o2.more.js | * |------------------------------------------------------------------------------| * | distributed under the agpl license: | * |------------------------------------------------------------------------------| * | 游戏厅捕鱼达人 copyright © 2018, o2oa.net, o2server.io o2 team | * | all rights reserved. | * |------------------------------------------------------------------------------| * * this file is part of o2oa. * * o2oa is free software: you can redistribute it and/or modify * it under the terms of the gnu affero general public license as published by * the free software foundation, either version 3 of the license, or * (at your option) any later version. * * o2oa is distributed in the hope that it will be useful, * but without any warranty; without even the implied warranty of * merchantability or fitness for a particular purpose. see the * gnu affero general public license for more details. * * you should have received a copy of the gnu general public license * along with foobar. if not, see . * * ***** end license block ******/ (function () { o2.getcenterposition = function (el, width, height) { var elpositon = $(el).getposition(); var elsize = $(el).getsize(); var node = $("layout"); var size = (node) ? $(node).getsize() : $(document.body).getsize(); var top = (elpositon.y elsize.y) / 2 - (height / 2); var left = (elpositon.x elsize.x) / 2 - (width / 2); if ((left width) > size.x) { left = size.x - width - 10; } if ((top height) > size.y) { top = size.y - height - 10; } return {"x": left, "y": top}; }; o2.getmarksize = function (node) { var size; if (!node) { size = $(document.body).getsize(); var winsize = $(window).getsize(); var height = size.y; var width = size.x; if (height < winsize.y) height = winsize.y; if (width < winsize.x) width = winsize.x; return {x: size.x, y: height}; } else { size = $(node).getsize(); return {x: size.x, y: size.y}; } }; o2.json = function (jsonstring, fun) { var obj = json.decode(jsonstring); var p = fun.split("."); var tmp = obj; p.each(function (item) { if (item.indexof("[") !== -1) { var x = item.split("["); var i = parseint(x[1].substr(0, x[1].indexof("]"))); tmp = tmp[x[0]][i]; } else { tmp = tmp[item]; } }); return tmp; }; o2.gethtmltemplate = function (url, callback, async) { var loadasync = (async !== false); var res = new request.html({ url: url, async: loadasync, method: "get", onsuccess: function (responsetree, responseelements, responsehtml, responsejavascript) { o2.runcallback(callback, "success", [responsetree, responseelements, responsehtml, responsejavascript]); }.bind(this), onfailure: function (xhr) { o2.runcallback(callback, "requestfailure", [xhr]); } }); res.send(); }; o2.getrequesttext = function (url, callback, async) { var loadasync = (async !== false); url = (url.indexof("?") !== -1) ? url "&v=" o2.version.v : url "?v=" o2.version.v; var res = new request({ url: url, async: loadasync, method: "get", onsuccess: function (responsetext, responsexml) { o2.runcallback(callback, "success", [responsetext, responsexml]); }.bind(this), onfailure: function (xhr) { o2.runcallback(callback, "requestfailure", [xhr]); } }); res.send(); }; o2.encodejsonstring = function (str) { var tmp = [str]; var datastr = (json.encode(tmp)); return datastr.substr(2, datastr.length - 4); }; o2.decodejsonstring = function (str) { var tmp = "[\"" str "\"]"; var dataobj = (json.decode(tmp)); return dataobj[0]; }; o2.gettextsize = function (text, styles) { var tmpspan = new element("span", { "text": text, "styles": styles }).inject($(document.body)); var size = tmpspan.getsize(); tmpspan.destroy(); return size; }; o2.getcenter = function (size, target, offset) { if (!target) target = document.body; var targetsize = target.getsize(); var targetposition = target.getposition(offset); var targetscroll = target.getscroll(); var x = targetsize.x / 2; var y = targetsize.y / 2; x = x - (size.x / 2); y = y - (size.y / 2); x = x targetposition.x; y = y targetposition.y; x = x targetscroll.x; y = y targetscroll.y; return {"x": x, "y": y}; }; o2.getepointer = function (e) { var x = 0; var y = 0; if (typeof(e) == "element") { var position = e.getposition(this.content); x = position.x; y = position.y; } else { if (browser.name == "firefox") { x = parsefloat(e.event.clientx || e.event.x); y = parsefloat(e.event.clienty || e.event.y); } else { x = parsefloat(e.event.x); y = parsefloat(e.event.y); } if (e.target) { var position = e.target.getposition(this.content); x = position.x; y = position.y; } // } } return {"x": x, "y": y}; }; o2.getparent = function (node, tag) { var pnode = node.parentelement; while (pnode && pnode.tagname.tostring().tolowercase() !== tag.tostring().tolowercase()) { pnode = pnode.parentelement; } return pnode; }; o2.getoffset = function (evt) { if (browser.name === "firefox") { return { "offsetx": evt.layerx, "offsety": evt.layery }; } else { return { "offsetx": evt.offsetx, "offsety": evt.offsety } } }; /** * @summary 对页面进行缩放。 * @function zoom * @memberof o2 * @param {number} [scale] 缩放的比例。1表示原始大小 * @o2syntax * o2.zoom(scale); * @example * //将页面放大到150%大小 * o2.zoom(1.5); */ o2.zoom = function (scale) { if (!layout) layout = {}; if (layout && !layout.userlayout) layout.userlayout = {}; layout.userlayout.scale = scale; // var s = (1 / layout.userlayout.scale) * 100; // var p = s "%"; // document.id(document.documentelement).setstyles({ // "transform": "scale(" layout.userlayout.scale ")", // "transform-origin": "0 0", // "width": p, // "height": p // }); document.body.style.zoom = scale; if (layout.desktop){ if (layout.desktop.resizeheight) layout.desktop.resizeheight(); } }; if (string.implement) string.implement({ "getallindexof": function (str) { var idxs = []; var idx = this.indexof(str); while (idx !== -1) { idxs.push(idx); idx = this.indexof(str, idx 1); } return idxs; } }); if (array.implement) array.implement({ "trim": function () { var arr = []; this.each(function (v) { if (v) arr.push(v); }); return arr; }, "isintersect": function (arr) { return this.some(function (item) { return (arr.indexof(item) !== -1); }) }, "add": function(newkey, newvalue, overwrite){ if (arguments.length<2){ this[this.length] = newkey; //this.push(newkey); }else{ if (o2.typeof(newkey)=="number"){ if (newkey=0 && p.y-srcoll.y>=0) && (p.x nodesize.x= 0 && p.y >= 0) && (p.x nodesize.x < size.x srcoll.x && p.y nodesize.y < size.y) }, "appendhtml": function (html, where) { if (this.insertadjacenthtml) { var wheretext = "beforeend"; if (where === "before") wheretext = "beforebegin"; if (where === "after") wheretext = "afterend"; if (where === "bottom") wheretext = "beforeend"; if (where === "top") wheretext = "afterbegin"; this.insertadjacenthtml(wheretext, html); } else { if (where === "bottom") this.innerhtml = this.innerhtml html; if (where === "top") this.innerhtml = html this.innerhtml; } }, "positionto": function (x, y) { var left = x.tofloat(); var top = y.tofloat(); var offsetnode = this.getoffsetparent(); if (offsetnode) { var offsetposition = offsetnode.getposition(); left = left - offsetposition.x; top = top - offsetposition.y; } this.setstyles({"top": top, "left": left}); return this; }, "getborder": function () { var positions = ["top", "left", "right", "bottom"]; var styles = ["color", "style", "width"]; var obj = {}; positions.each(function (position) { styles.each(function (style) { var key = "border-" position "-" style; obj[key] = this.getstyle(key); }.bind(this)); }.bind(this)); return obj; }, "isoutside": function (e) { var elementcoords = this.getcoordinates(); var targetcoords = this.getcoordinates(); if (((e.page.x < elementcoords.left || e.page.x > (elementcoords.left elementcoords.width)) || (e.page.y < elementcoords.top || e.page.y > (elementcoords.top elementcoords.height))) && ((e.page.x < targetcoords.left || e.page.x > (targetcoords.left targetcoords.width)) || (e.page.y < targetcoords.top || e.page.y > (targetcoords.top targetcoords.height)))) return true; return false; }, "getabsoluteposition": function () { var styleleft = 0; var styletop = 0; var node = this; styleleft = node.offsetleft; styletop = node.offsettop; node = node.parentelement; while (node && node.tagname.tostring().tolowercase() !== "body") { styleleft = node.offsetleft; styletop = node.offsettop; node = node.offsetparent; } return {x: styleleft, y: styletop}; }, "tweenscroll": function (to, time) { if (!this.tweenscrollqueue) { this.tweenscrollqueue = []; } if (this.tweenscrollqueue.length) { this.tweenscrollqueue.push(to); } else { this.tweenscrollqueue.push(to); this.dotweenscrollqueue(time); } }, "dotweenscrollqueue": function (time) { if (this.tweenscrollqueue.length) { var i = this.tweenscrollqueue.length; var to = this.tweenscrollqueue[this.tweenscrollqueue.length - 1]; var scroll = this.getscroll(); var dy = to - scroll.y; var step = dy / time; var count = 0; var move = 0; var id = window.setinterval(function () { this.scrollto(0, scroll.y count * step); count ; if (count > time) { window.clearinterval(id); for (var x = 1; x <= i; x ) this.tweenscrollqueue.shift(); if (this.tweenscrollqueue.length) this.dotweenscrollqueue(time); } }.bind(this), 1); } }, "ispointin": function (px, py, offx, offy, el) { if (!offx) offx = 0; if (!offy) offy = 0; var position = this.getposition(el); var size = this.getsize(); return (position.x - offx <= px && position.x size.x offx >= px && position.y - offy <= py && position.y size.y offy >= py); }, "isinpointinrect": function (sx, sy, ex, ey) { var position = this.getposition(); var size = this.getsize(); var p1 = {"x": position.x, "y": position.y}; var p2 = {"x": position.x size.x, "y": position.y}; var p3 = {"x": position.x size.x, "y": position.y size.y}; var p4 = {"x": position.x, "y": position.y size.y}; var sp = {"x": math.min(sx, ex), "y": math.min(sy, ey)}; var ep = {"x": math.max(sx, ex), "y": math.max(sy, ey)}; if (p1.x >= sp.x && p1.y >= sp.y && p1.x <= ep.x && p1.y <= ep.y) return true; if (p2.x >= sp.x && p2.y >= sp.y && p2.x <= ep.x && p2.y <= ep.y) return true; if (p3.x >= sp.x && p3.y >= sp.y && p3.x <= ep.x && p3.y <= ep.y) return true; if (p4.x >= sp.x && p4.y >= sp.y && p4.x <= ep.x && p4.y <= ep.y) return true; if (p3.x >= sp.x && p3.y >= sp.y && p1.x <= sp.x && p1.y <= sp.y) return true; if (p3.x >= ep.x && p3.y >= ep.y && p1.x <= ep.x && p1.y <= ep.y) return true; if (p1.x <= sp.x && p2.x >= sp.x && p1.y >= sp.y && p4.y <= ep.y) return true; if (p1.y <= sp.y && p4.y >= sp.y && p1.x >= sp.x && p2.x <= ep.x) return true; return false; }, "isoverlap": function (node) { var p = node.getposition(); var s = node.getsize(); return this.isinpointinrect(p.x, p.y, p.x s.x, p.y s.y); }, "getusefulsize": function () { var size = this.getsize(); var borderleft = this.getstyle("border-left").toint(); var borderbottom = this.getstyle("border-bottom").toint(); var bordertop = this.getstyle("border-top").toint(); var borderright = this.getstyle("border-right").toint(); var paddingleft = this.getstyle("padding-left").toint(); var paddingbottom = this.getstyle("padding-bottom").toint(); var paddingtop = this.getstyle("padding-top").toint(); var paddingright = this.getstyle("padding-right").toint(); var x = size.x - paddingleft - paddingright; var y = size.y - paddingtop - paddingbottom; return {"x": x, "y": y}; }, "clearstyles": function (ischild) { this.removeproperty("style"); if (ischild) { var subnode = this.getfirst(); while (subnode) { subnode.clearstyles(ischild); subnode = subnode.getnext(); } } }, "maskif": function (styles, click) { var style = { "background-color": "#666666", "opacity": 0.4, "z-index": 100 }; if (styles) { style = object.merge(style, styles); } var position = this.getposition(this.getoffsetparent()); this.mask({ "destroyonhide": true, "style": style, "useiframeshim": true, "iframeshimoptions": {"browsers": true}, "onshow": function () { this.shim.shim.setstyles({ "opacity": 0, "top": "" position.y "px", "left": "" position.x "px" }); }, "onclick": click }); }, "scrollin": function (where) { var wh = (where) ? where.tostring().tolowercase() : "center"; if (browser.name == "ie" || browser.name == "safari") { var scrollnode = this.getparentsrcollnode(); var scrollfx = new fx.scroll(scrollnode); var scroll = scrollnode.getscroll(); var size = scrollnode.getsize(); var thissize = this.getcomputedsize(); var p = this.getposition(scrollnode); if (wh == "start") { var top = 0; scrollfx.start(scroll.x, p.y - top scroll.y); } else if (wh == "end") { var bottom = size.y - thissize.totalheight; scrollfx.start(scroll.x, p.y - bottom scroll.y); } else { var center = size.y / 2 - thissize.totalheight / 2; scrollfx.start(scroll.x, p.y - center scroll.y); } } else { if (wh !== "start" && wh !== "end") wh = "center" this.scrollintoview({"behavior": "smooth", "block": wh, "inline": "nearest"}); } }, scrolltonode: function (el, where) { var scrollsize = this.getscrollsize(); if (!scrollsize.y) return true; var wh = (where) ? where.tostring().tolowercase() : "bottom"; var node = $(el); var size = node.getcomputedsize(); var p = node.getposition(this); var thissize = this.getcomputedsize(); var scroll = this.getscroll(); if (wh === "top") { var n = (p.y - thissize.computedtop); if (n < 0) this.scrollto(scroll.x, scroll.y n); n = (size.totalheight p.y - thissize.computedtop) - thissize.height; if (n > 0) this.scrollto(scroll.x, scroll.y n); } else { var n = (size.totalheight p.y - thissize.computedtop) - thissize.height; if (n > 0) this.scrollto(scroll.x, scroll.y n); n = p.y - thissize.computedtop; if (n < 0) this.scrollto(scroll.x, scroll.y n); } }, "getinnerstyles": function () { var styles = {}; style = this.get("style"); if (style) { var stylearr = style.split(/\s*\;\s*/g); stylearr.each(function (s) { if (s) { var sarr = s.split(/\s*\:\s*/g); styles[sarr[0]] = (sarr.length > 1) ? sarr[1] : "" } }.bind(this)); } return styles; }, "getinnerproperties": function () { var properties = {}; if (this.attributes.length) { for (var i = 0; i < this.attributes.length; i ) { properties[this.attributes[i].nodename] = this.attributes[i].nodevalue; } } return properties; }, "getzindex": function () { var n = this; var i = 0; while (n) { if (n.getstyle("position") === "absolute") { var idx = n.getstyle("z-index"); i = (idx && idx.tofloat() > i) ? idx.tofloat() 1 : 0; break; } n = n.getparent(); } return i; }, "getparentsrcollnode": function () { var node = this.getparent(); while (node && (node.getscrollsize().y - 2 <= node.getsize().y || (node.getstyle("overflow") !== "auto" && node.getstyle("overflow-y") !== "auto"))) { node = node.getparent(); } return node || null; }, "getedgeheight": function (notmargin) { var h = 0; h = (this.getstyle("border-top-width").tofloat() || 0) (this.getstyle("border-bottom-width").tofloat() || 0); h = (this.getstyle("padding-top").tofloat() || 0) (this.getstyle("padding-bottom").tofloat() || 0); if (!notmargin) h = (this.getstyle("margin-top").tofloat() || 0) (this.getstyle("margin-bottom").tofloat() || 0); return h; }, "getedgewidth": function (notmargin) { var h = 0; h = (this.getstyle("border-left-width").tofloat() || 0) (this.getstyle("border-right-width").tofloat() || 0); h = (this.getstyle("padding-left").tofloat() || 0) (this.getstyle("padding-right").tofloat() || 0); if (!notmargin) h = (this.getstyle("margin-left").tofloat() || 0) (this.getstyle("margin-right").tofloat() || 0); return h; }, "getsize": function () { if ((/^(?:body|html)$/i).test(this.tagname)) return this.getwindow().getsize(); if (!window.getcomputedstyle) return {x: this.offsetwidth, y: this.offsetheight}; if (this.get('tag') == 'svg') return svgcalculatesize(this); try { if (!layout || !layout.userlayout || !layout.userlayout.scale || layout.userlayout.scale == 1) { var bounds = this.getboundingclientrect(); return {x: bounds.width, y: bounds.height}; } else { return {"x": this.offsetwidth.tofloat(), "y": this.offsetheight.tofloat()}; } } catch (e) { return {x: 0, y: 0}; } }, "getscaleoffsets": function () { var hasgetboundingclientrect = this.getboundingclientrect; //<1.4compat> //hasgetboundingclientrect = hasgetboundingclientrect && !browser.platform.ios; // if (hasgetboundingclientrect) { var bound = this.getboundingclientrect(); var boundleft = bound.left; var boundtop = bound.top; if (!layout || !layout.userlayout || !layout.userlayout.scale || layout.userlayout.scale == 1) { } else { // boundleft = boundleft / layout.userlayout.scale; // boundtop = boundtop / layout.userlayout.scale; } var html = document.id(this.getdocument().documentelement); var htmlscroll = html.getscroll(); var elemscrolls = this.getscrolls(); var isfixed = (element.getcomputedstyle(this, 'position') == 'fixed'); return { x: boundleft.tofloat() elemscrolls.x ((isfixed) ? 0 : htmlscroll.x) - html.clientleft, y: boundtop.tofloat() elemscrolls.y ((isfixed) ? 0 : htmlscroll.y) - html.clienttop }; } var element = this, position = {x: 0, y: 0}; if (isbody(this)) return position; while (element && !isbody(element)) { position.x = element.offsetleft; position.y = element.offsettop; //<1.4compat> if (browser.firefox) { if (!borderbox(element)) { position.x = leftborder(element); position.y = topborder(element); } var parent = element.parentnode; if (parent && stylestring(parent, 'overflow') != 'visible') { position.x = leftborder(parent); position.y = topborder(parent); } } else if (element != this && browser.safari) { position.x = leftborder(element); position.y = topborder(element); } // element = element.offsetparent; } //<1.4compat> if (browser.firefox && !borderbox(this)) { position.x -= leftborder(this); position.y -= topborder(this); } // return position; }, getposition: function (relative) { var offset = this.getscaleoffsets(), scroll = this.getscrolls(); var position = { x: offset.x - scroll.x, y: offset.y - scroll.y }; if (relative && (relative = document.id(relative))) { var relativeposition = relative.getposition(); return { x: position.x - relativeposition.x - leftborder(relative), y: position.y - relativeposition.y - topborder(relative) }; } return position; } }); object.copy = function (from, to) { object.each(from, function (value, key) { switch (typeof(value)) { case "object": if (!to[key]) to[key] = {}; object.copy(value, to[key]); break; default: to[key] = value; } }); }; if (window.json) json.format = json.encode; if (window.slick) { slick.definepseudo('src', function (value) { return element.get(this, "src").indexof(value) !== -1; }); slick.definepseudo('srcarr', function (value) { var vlist = value.split(","); var src = element.get(this, "src"); var flag = false; for (var i = 0; i < vlist.length; i ) { if (src.indexof(vlist[i]) !== -1) { flag = true; break; } } return flag; }); slick.definepseudo('ahref', function (value) { var href = element.get(this, "href"); if (!href) href = ""; href = href.tostring().tolowercase(); return (href.indexof(value) !== -1); }); slick.definepseudo('rowspanbefore', function (line) { var tr = mwf.getparent(this, "tr"); var rowspan = this.get("rowspan").toint() || 1; var currentrowindex = tr.rowindex.toint(); return rowspan > 1 && currentrowindex < line.toint() && currentrowindex rowspan - 1 >= line; }); slick.definepseudo('rowspan', function () { var rowspan = this.get("rowspan").toint() || 1; return rowspan > 1; }); slick.definepseudo('colspanbefore', function (col) { var tr = mwf.getparent(this, "tr"); var colspan = this.get("colspan").toint() || 1; var currentcolindex = this.cellindex.toint(); return colspan > 1 && currentcolindex < col.toint() && currentcolindex colspan - 1 >= col.toint(); }); slick.definepseudo('colspan', function () { var colspan = this.get("colspan").toint() || 1; return colspan > 1; }); } // 第三方扩展用的函数 o2.thirdparty = o2.thirdparty || {}; // 是否手机端 o2.thirdparty.ismobile = function(){ return /(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone)/i.test(navigator.useragent.tolowercase()); } function alwaysfalse() { return false; } if (o2.thirdparty.ismobile()) { // 手机端钉钉 o2.thirdparty.isdingdingmobile = function() { var isdingding = /dingtalk/i.test(navigator.useragent.tolowercase()) return isdingding && o2.thirdparty.ismobile(); } //手机端企业微信 o2.thirdparty.isqywxmobile = function() { var iscomwx = /wxwork/i.test(navigator.useragent); // 是否企业微信 return (iscomwx && o2.thirdparty.ismobile()); } //手机端微信 o2.thirdparty.isweixinmobile = function() { var iswx = /micromessenger/i.test(navigator.useragent); // 是否微信 return (iswx && o2.thirdparty.ismobile()); } o2.thirdparty.isdingdingpc = alwaysfalse; o2.thirdparty.isqywxpc = alwaysfalse; o2.thirdparty.isweixinpc = alwaysfalse; } else { o2.thirdparty.isdingdingmobile = alwaysfalse; o2.thirdparty.isqywxmobile = alwaysfalse; o2.thirdparty.isweixinmobile = alwaysfalse; // pc端钉钉 o2.thirdparty.isdingdingpc = function() { var isdingding = /dingtalk/i.test(navigator.useragent.tolowercase()) return isdingding && !o2.thirdparty.ismobile(); } //pc端企业微信 o2.thirdparty.isqywxpc = function() { var iscomwx = /wxwork/i.test(navigator.useragent); // 是否企业微信 return (iscomwx && !o2.thirdparty.ismobile()); } //pc端微信 o2.thirdparty.isweixinpc = function() { var iswx = /micromessenger/i.test(navigator.useragent); // 是否微信 return (iswx && !o2.thirdparty.ismobile()); } } o2.common = o2.common || {}; o2.common.encodehtml = function (str) { str = str.tostring(); str = str.replace(/\&/g, "&"); str = str.replace(/>/g, ">"); str = str.replace(/ size.x) { //fromx = fromx 20; x = fromx - parsefloat(width); }else{ fromx = x; //if (x < 0) x = 20; } if (fromy parsefloat(height) > size.y) { y = fromy - parsefloat(height); //y = y - 20; }else{ y = fromy; // if (y < 0) y = 0; // y = y 20; } return { "x": x, "y": y, "fromx": fromx, "fromy": fromy } }; if (window.browser) { if (browser.name === "ie" && browser.version < 9) { browser.ieuns = true; } else if (browser.name === "ie" && browser.version < 10) { browser.iecomp = true; } if (browser.iecomp) { o2.load("ie_adapter", null, false); o2.session.isdebugger = true; } o2.session.ismobile = (["mac", "win", "linux"].indexof(browser.platform.name) === -1); } })(); o2.more = true; //o2.addready (function () { //dom ready var _dom; if (window.document) { _dom = { ready: false, loaded: false, checks: [], shouldpoll: false, timer: null, testelement: document.createelement('div'), readys: [], domready: function () { cleartimeout(_dom.timer); if (_dom.ready) return; _dom.loaded = _dom.ready = true; o2.removelistener(document, 'domcontentloaded', _dom.checkready); o2.removelistener(document, 'readystatechange', _dom.check); _dom.onready(); }, check: function () { for (var i = _dom.checks.length; i--;) if (_dom.checks[i]() && window.mootools && o2.core && o2.more) { _dom.domready(); return true; } return false; }, poll: function () { cleartimeout(_dom.timer); if (!_dom.check()) _dom.timer = settimeout(_dom.poll, 10); }, /**/ // doscroll technique by diego perini http://javascript.nwbox.com/iecontentloaded/ // testelement.doscroll() throws when the dom is not ready, only in the top window doscrollworks: function () { try { _dom.testelement.doscroll(); return true; } catch (e) { } return false; }, /**/ onready: function () { for (var i = 0; i < _dom.readys.length; i ) { this.readys[i].apply(window); } }, addready: function (fn) { if (_dom.loaded) { if (fn) fn.apply(window); } else { if (fn) _dom.readys.push(fn); } return _dom; }, checkready: function () { _dom.checks.push(function () { return true }); _dom.check(); } }; o2.addlistener(document, 'domcontentloaded', _dom.checkready); /**/ // if doscroll works already, it can't be used to determine domready // e.g. in an iframe if (_dom.testelement.doscroll && !_dom.doscrollworks()) { _dom.checks.push(_dom.doscrollworks); _dom.shouldpoll = true; } /**/ if (document.readystate) _dom.checks.push(function () { var state = document.readystate; return (state == 'loaded' || state == 'complete'); }); if ('onreadystatechange' in document) o2.addlistener(document, 'readystatechange', _dom.check); else _dom.shouldpoll = true; if (_dom.shouldpoll) _dom.poll(); } else { _dom = { ready: false, loaded: false, checks: [], shouldpoll: false, timer: null, readys: [], domready: function () { cleartimeout(_dom.timer); if (_dom.ready) return; _dom.loaded = _dom.ready = true; _dom.onready(); }, check: function () { if (window.mootools && o2.core && o2.more) { _dom.domready(); return true; } return false; }, onready: function () { for (var i = 0; i < _dom.readys.length; i ) { this.readys[i].apply(window); } }, addready: function (fn) { if (_dom.loaded) { if (fn) fn.apply(window); } else { if (fn) _dom.readys.push(fn); } return _dom; }, checkready: function () { _dom.checks.push(function () { return true }); _dom.check(); } }; } var _loado2 = function () { (!o2.core) ? this.o2.load("o2.core", _dom.check) : _dom.check(); (!o2.more) ? this.o2.load("o2.more", _dom.check) : _dom.check(); }; if (!window.mootools) { this.o2.load("mootools", function () { _loado2(); _dom.check(); }); } else { _loado2(); } this.o2.addready = function (fn) { _dom.addready.call(_dom, fn); }; })(); //compatible common = { "dom": {}, "setcontentpath": function (path) { common.contentpath = path; }, "json": o2.json, "browser": window.browser, "class": o2.class, "xml": o2.xml, "ajaxmodule": { "load": function (urls, callback, async, reload) { o2.load(urls, callback, reload, document); }, "loaddom": function (urls, callback, async, reload) { o2.load(urls, callback, reload, document); }, "loadcss": function (urls, callback, async, reload, sourcedoc) { o2.loadcss(urls, document.body, callback, reload, sourcedoc); } }, "request": request, "typeof": o2.typeof }; if (common.browser) common.browser.platform.ismobile = o2.session.ismobile; common.dom.addready = o2.addready; mwf = o2; mwf.getjson = o2.json.get; mwf.getjsonp = o2.json.getjsonp; mwf.defaultpath = o2.session.path; }
网站地图