diff --git a/.eslintrc b/.eslintrc index 3fbfc3524..eee30f2c7 100644 --- a/.eslintrc +++ b/.eslintrc @@ -27,7 +27,7 @@ "plugins": ["@typescript-eslint/eslint-plugin"], "overrides": [{ "files": ["src/*.js","src/**/*.js", "demo/*.js", "demo/**/*.js", "i18n/**/*.js", "i18n/*.js", "test/**/*.js", "test/*.js", "examples/*.js", "examples/**/*.js"], - "extends": "plugin:@fui/es5", + "extends": "plugin:@fui/es6", "rules": { "no-param-reassign": "off", "quotes": [2, "double"], diff --git a/src/core/2.base.js b/src/core/2.base.js index 63ff1821d..0f0914be3 100644 --- a/src/core/2.base.js +++ b/src/core/2.base.js @@ -3,1278 +3,1279 @@ * Create By GUY 2014\11\17 * */ -!(function (undefined) { - var traverse = function (func, context) { - return function (value, key, obj) { - return func.call(context, key, value, obj); - }; +var traverse = function (func, context) { + return function (value, key, obj) { + return func.call(context, key, value, obj); }; - var _apply = function (name) { - return function () { - return BI._[name].apply(BI._, arguments); - }; +}; +var _apply = function (name) { + return function () { + return BI._[name].apply(BI._, arguments); }; - var _applyFunc = function (name) { - return function () { - var args = Array.prototype.slice.call(arguments, 0); - args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; - return BI._[name].apply(BI._, args); - }; +}; +var _applyFunc = function (name) { + return function () { + var args = Array.prototype.slice.call(arguments, 0); + args[1] = BI._.isFunction(args[1]) ? traverse(args[1], args[2]) : args[1]; + return BI._[name].apply(BI._, args); }; +}; - // Utility - BI._.extend(BI, { - assert: function (v, is) { - if (this.isFunction(is)) { - if (!is(v)) { - throw new Error(v + " error"); - } else { - return true; - } - } - if (!this.isArray(is)) { - is = [is]; - } - if (!this.deepContains(is, v)) { +// Utility +BI._.extend(BI, { + assert: function (v, is) { + if (this.isFunction(is)) { + if (!is(v)) { throw new Error(v + " error"); + } else { + return true; } - return true; - }, - - warn: function (message) { - console.warn(message); - }, - - UUID: function () { - var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; - var str = ""; - for (var i = 0; i < 16; i++) { - var r = parseInt(f.length * Math.random(), 10); - str += f[r]; - } - return str; - }, + } + if (!this.isArray(is)) { + is = [is]; + } + if (!this.deepContains(is, v)) { + throw new Error(v + " error"); + } + return true; + }, + + warn: function (message) { + console.warn(message); + }, + + UUID: function () { + var f = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; + var str = ""; + for (var i = 0; i < 16; i++) { + var r = parseInt(f.length * Math.random(), 10); + str += f[r]; + } + return str; + }, - isWidget: function (widget) { - return widget instanceof BI.Widget; - }, + isWidget: function (widget) { + return widget instanceof BI.Widget; + }, - createWidgets: function (items, options, context) { - if (!BI.isArray(items)) { - throw new Error("items必须是数组", items); + createWidgets: function (items, options, context) { + if (!BI.isArray(items)) { + throw new Error("items必须是数组", items); + } + if (BI.isWidget(options)) { + context = options; + options = {}; + } else { + options || (options = {}); + } + return BI.map(BI.flatten(items), function (i, item) { + return BI.createWidget(item, BI.deepClone(options), context); + }); + }, + + createItems: function (data, innerAttr, outerAttr) { + innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); + outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); + return BI.map(data, function (i, item) { + if (BI.isArray(item)) { + return BI.createItems(item, innerAttr, outerAttr); + } + if (item instanceof BI.Widget) { + return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { + type: null, + el: item + }); } - if (BI.isWidget(options)) { - context = options; - options = {}; - } else { - options || (options = {}); + if (innerAttr[0] instanceof BI.Widget) { + outerAttr.shift(); + return BI.extend({}, item, { + el: innerAttr.shift() + }); } - return BI.map(BI.flatten(items), function (i, item) { - return BI.createWidget(item, BI.deepClone(options), context); - }); - }, - - createItems: function (data, innerAttr, outerAttr) { - innerAttr = BI.isArray(innerAttr) ? innerAttr : BI.makeArray(BI.flatten(data).length, innerAttr || {}); - outerAttr = BI.isArray(outerAttr) ? outerAttr : BI.makeArray(BI.flatten(data).length, outerAttr || {}); - return BI.map(data, function (i, item) { - if (BI.isArray(item)) { - return BI.createItems(item, innerAttr, outerAttr); - } - if (item instanceof BI.Widget) { - return BI.extend({}, innerAttr.shift(), outerAttr.shift(), { - type: null, - el: item - }); - } - if (innerAttr[0] instanceof BI.Widget) { - outerAttr.shift(); - return BI.extend({}, item, { - el: innerAttr.shift() - }); - } - if (item.el instanceof BI.Widget) { - innerAttr.shift(); - return BI.extend({}, outerAttr.shift(), { type: null }, item); - } - if (item.el) { - return BI.extend({}, outerAttr.shift(), item, { - el: BI.extend({}, innerAttr.shift(), item.el) - }); - } - return BI.extend({}, outerAttr.shift(), { - el: BI.extend({}, innerAttr.shift(), item) + if (item.el instanceof BI.Widget) { + innerAttr.shift(); + return BI.extend({}, outerAttr.shift(), { type: null }, item); + } + if (item.el) { + return BI.extend({}, outerAttr.shift(), item, { + el: BI.extend({}, innerAttr.shift(), item.el) }); + } + return BI.extend({}, outerAttr.shift(), { + el: BI.extend({}, innerAttr.shift(), item) }); - }, - - // 用容器包装items - packageItems: function (items, layouts) { - for (var i = layouts.length - 1; i >= 0; i--) { - items = BI.map(items, function (k, it) { - return BI.extend({}, layouts[i], { - items: [ - BI.extend({}, layouts[i].el, { - el: it - }) - ] - }); + }); + }, + + // 用容器包装items + packageItems: function (items, layouts) { + for (var i = layouts.length - 1; i >= 0; i--) { + items = BI.map(items, function (k, it) { + return BI.extend({}, layouts[i], { + items: [ + BI.extend({}, layouts[i].el, { + el: it + }) + ] }); - } - return items; - }, - - formatEL: function (obj) { - if (obj && !obj.type && obj.el) { - return obj; - } - return { - el: obj - }; - }, - - // 剥开EL - stripEL: function (obj) { - return obj.type && obj || obj.el || obj; - }, - - trans2Element: function (widgets) { - return BI.map(widgets, function (i, wi) { - return wi.element; }); } - }); + return items; + }, - // 集合相关方法 - BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", - "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { - if (name === "any") { - BI[name] = _applyFunc("some"); - } else { - BI[name] = _applyFunc(name); - } - }); - BI._.extend(BI, { - // 数数 - count: function (from, to, predicate) { - var t; - if (predicate) { - for (t = from; t < to; t++) { - predicate(t); - } + formatEL: function (obj) { + if (obj && !obj.type && obj.el) { + return obj; + } + return { + el: obj + }; + }, + + // 剥开EL + stripEL: function (obj) { + return obj.type && obj || obj.el || obj; + }, + + trans2Element: function (widgets) { + return BI.map(widgets, function (i, wi) { + return wi.element; + }); + } +}); + +// 集合相关方法 +BI._.each(["where", "findWhere", "invoke", "pluck", "shuffle", "sample", "toArray", "size"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["get", "set", "each", "map", "reduce", "reduceRight", "find", "filter", "reject", "every", "all", "some", "any", "max", "min", + "sortBy", "groupBy", "indexBy", "countBy", "partition", "clamp"], function (name) { + if (name === "any") { + BI[name] = _applyFunc("some"); + } else { + BI[name] = _applyFunc(name); + } +}); +BI._.extend(BI, { + // 数数 + count: function (from, to, predicate) { + var t; + if (predicate) { + for (t = from; t < to; t++) { + predicate(t); } - return to - from; - }, - - // 倒数 - inverse: function (from, to, predicate) { - return BI.count(to, from, predicate); - }, - - firstKey: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, - - lastKey: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = key; - return true; - }); - return res; - }, + } + return to - from; + }, + + // 倒数 + inverse: function (from, to, predicate) { + return BI.count(to, from, predicate); + }, + + firstKey: function (obj) { + var res = undefined; + BI.any(obj, function (key, value) { + res = key; + return true; + }); + return res; + }, + + lastKey: function (obj) { + var res = undefined; + BI.each(obj, function (key, value) { + res = key; + return true; + }); + return res; + }, + + firstObject: function (obj) { + var res = undefined; + BI.any(obj, function (key, value) { + res = value; + return true; + }); + return res; + }, + + lastObject: function (obj) { + var res = undefined; + BI.each(obj, function (key, value) { + res = value; + return true; + }); + return res; + }, + + concat: function (obj1, obj2) { + if (BI.isKey(obj1)) { + return BI.map([].slice.apply(arguments), function (idx, v) { + return v; + }).join(""); + } + if (BI.isArray(obj1)) { + return BI._.concat.apply([], arguments); + } + if (BI.isObject(obj1)) { + return BI._.extend.apply({}, arguments); + } + }, - firstObject: function (obj) { - var res = undefined; - BI.any(obj, function (key, value) { - res = value; - return true; - }); - return res; - }, + backEach: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + predicate(index, obj[index], obj); + } + return false; + }, - lastObject: function (obj) { - var res = undefined; - BI.each(obj, function (key, value) { - res = value; + backAny: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + if (predicate(index, obj[index], obj)) { return true; - }); - return res; - }, - - concat: function (obj1, obj2) { - if (BI.isKey(obj1)) { - return BI.map([].slice.apply(arguments), function (idx, v) { - return v; - }).join(""); } - if (BI.isArray(obj1)) { - return BI._.concat.apply([], arguments); - } - if (BI.isObject(obj1)) { - return BI._.extend.apply({}, arguments); - } - }, + } + return false; + }, - backEach: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - predicate(index, obj[index], obj); + backEvery: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + for (var index = obj.length - 1; index >= 0; index--) { + if (!predicate(index, obj[index], obj)) { + return false; } - return false; - }, + } + return true; + }, - backAny: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (predicate(index, obj[index], obj)) { - return true; - } + backFindKey: function (obj, predicate, context) { + predicate = BI.iteratee(predicate, context); + var keys = BI._.keys(obj), key; + for (var i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if (predicate(obj[key], key, obj)) { + return key; } - return false; - }, + } + }, - backEvery: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - for (var index = obj.length - 1; index >= 0; index--) { - if (!predicate(index, obj[index], obj)) { - return false; + backFind: function (obj, predicate, context) { + var key; + if (BI.isArray(obj)) { + key = BI.findLastIndex(obj, predicate, context); + } else { + key = BI.backFindKey(obj, predicate, context); + } + if (key !== void 0 && key !== -1) { + return obj[key]; + } + }, + + remove: function (obj, target, context) { + var isFunction = BI.isFunction(target); + target = isFunction || BI.isArray(target) ? target : [target]; + var i; + if (BI.isArray(obj)) { + for (i = 0; i < obj.length; i++) { + if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { + obj.splice(i--, 1); } } - return true; - }, - - backFindKey: function (obj, predicate, context) { - predicate = BI.iteratee(predicate, context); - var keys = BI._.keys(obj), key; - for (var i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if (predicate(obj[key], key, obj)) { - return key; + } else { + BI.each(obj, function (i, v) { + if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { + delete obj[i]; } - } - }, + }); + } + }, - backFind: function (obj, predicate, context) { - var key; - if (BI.isArray(obj)) { - key = BI.findLastIndex(obj, predicate, context); - } else { - key = BI.backFindKey(obj, predicate, context); - } - if (key !== void 0 && key !== -1) { - return obj[key]; - } - }, - - remove: function (obj, target, context) { - var isFunction = BI.isFunction(target); - target = isFunction || BI.isArray(target) ? target : [target]; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - obj.splice(i--, 1); - } - } + removeAt: function (obj, index) { + index = BI.isArray(index) ? index : [index]; + var isArray = BI.isArray(obj), i; + for (i = 0; i < index.length; i++) { + if (isArray) { + obj[index[i]] = "$deleteIndex"; } else { - BI.each(obj, function (i, v) { - if ((isFunction && (target === obj[i] || target.apply(context, [i, obj[i]]) === true)) || (!isFunction && BI.contains(target, obj[i]))) { - delete obj[i]; - } - }); + delete obj[index[i]]; } - }, - - removeAt: function (obj, index) { - index = BI.isArray(index) ? index : [index]; - var isArray = BI.isArray(obj), i; - for (i = 0; i < index.length; i++) { - if (isArray) { - obj[index[i]] = "$deleteIndex"; - } else { - delete obj[index[i]]; - } - } - if (isArray) { - BI.remove(obj, "$deleteIndex"); + } + if (isArray) { + BI.remove(obj, "$deleteIndex"); + } + }, + + string2Array: function (str) { + return str.split("&-&"); + }, + + array2String: function (array) { + return array.join("&-&"); + }, + + abc2Int: function (str) { + var idx = 0, start = "A", str = str.toUpperCase(); + for (var i = 0, len = str.length; i < len; ++i) { + idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; + if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { + return 0; } - }, - - string2Array: function (str) { - return str.split("&-&"); - }, - - array2String: function (array) { - return array.join("&-&"); - }, - - abc2Int: function (str) { - var idx = 0, start = "A", str = str.toUpperCase(); - for (var i = 0, len = str.length; i < len; ++i) { - idx = str.charAt(i).charCodeAt(0) - start.charCodeAt(0) + 26 * idx + 1; - if (idx > (2147483646 - str.charAt(i).charCodeAt(0) + start.charCodeAt(0)) / 26) { - return 0; - } + } + return idx; + }, + + int2Abc: function (num) { + var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; + var idx = num, str = ""; + if (num === 0) { + return ""; + } + while (idx !== 0) { + var t = idx % 26; + if (t === 0) { + t = 26; } - return idx; - }, - - int2Abc: function (num) { - var DIGITS = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; - var idx = num, str = ""; - if (num === 0) { - return ""; + str = DIGITS[t - 1] + str; + idx = (idx - t) / 26; + } + return str; + } +}); + +// 数组相关的方法 +BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", + "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["findIndex", "findLastIndex"], function (name) { + BI[name] = _applyFunc(name); +}); +BI._.extend(BI, { + // 构建一个长度为length的数组 + makeArray: function (length, value) { + var res = []; + for (var i = 0; i < length; i++) { + if (BI.isNull(value)) { + res.push(i); + } else { + res.push(BI.deepClone(value)); } - while (idx !== 0) { - var t = idx % 26; - if (t === 0) { - t = 26; - } - str = DIGITS[t - 1] + str; - idx = (idx - t) / 26; + } + return res; + }, + + makeObject: function (array, value) { + var map = {}; + for (var i = 0; i < array.length; i++) { + if (BI.isNull(value)) { + map[array[i]] = array[i]; + } else if (BI.isFunction(value)) { + map[array[i]] = value(i, array[i]); + } else { + map[array[i]] = BI.deepClone(value); } - return str; } - }); + return map; + }, - // 数组相关的方法 - BI._.each(["first", "initial", "last", "rest", "compact", "flatten", "without", "union", "intersection", - "difference", "zip", "unzip", "object", "indexOf", "lastIndexOf", "sortedIndex", "range", "take", "takeRight", "uniqBy"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["findIndex", "findLastIndex"], function (name) { - BI[name] = _applyFunc(name); - }); - BI._.extend(BI, { - // 构建一个长度为length的数组 - makeArray: function (length, value) { - var res = []; - for (var i = 0; i < length; i++) { - if (BI.isNull(value)) { - res.push(i); - } else { - res.push(BI.deepClone(value)); - } - } + makeArrayByArray: function (array, value) { + var res = []; + if (!array) { return res; - }, - - makeObject: function (array, value) { - var map = {}; - for (var i = 0; i < array.length; i++) { - if (BI.isNull(value)) { - map[array[i]] = array[i]; - } else if (BI.isFunction(value)) { - map[array[i]] = value(i, array[i]); - } else { - map[array[i]] = BI.deepClone(value); - } + } + for (var i = 0, len = array.length; i < len; i++) { + if (BI.isArray(array[i])) { + res.push(BI.makeArrayByArray(array[i], value)); + } else { + res.push(BI.deepClone(value)); } - return map; - }, + } + return res; + }, - makeArrayByArray: function (array, value) { - var res = []; - if (!array) { - return res; - } - for (var i = 0, len = array.length; i < len; i++) { - if (BI.isArray(array[i])) { - res.push(BI.makeArrayByArray(array[i], value)); - } else { - res.push(BI.deepClone(value)); - } - } - return res; - }, + uniq: function (array, isSorted, iteratee, context) { + if (array == null) { + return []; + } + if (!BI._.isBoolean(isSorted)) { + context = iteratee; + iteratee = isSorted; + isSorted = false; + } + iteratee && (iteratee = traverse(iteratee, context)); + return BI._.uniq.call(BI._, array, isSorted, iteratee, context); + } +}); + +// 对象相关方法 +BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", + "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", + "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", + "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { + BI[name] = _apply(name); +}); +BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { + BI[name] = _applyFunc(name); +}); +BI._.extend(BI, { + + inherit: function (sp, overrides) { + var sb = function () { + return sp.apply(this, arguments); + }; + var F = function () { + }, spp = sp.prototype; + F.prototype = spp; + sb.prototype = new F(); + sb.superclass = spp; + BI._.extend(sb.prototype, overrides, { + superclass: sp + }); + return sb; + }, + + init: function () { + // 先把准备环境准备好 + while (BI.prepares && BI.prepares.length > 0) { + BI.prepares.shift()(); + } + while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { + _global.___fineuiExposedFunction.shift()(); + } + BI.initialized = true; + }, - uniq: function (array, isSorted, iteratee, context) { - if (array == null) { - return []; - } - if (!BI._.isBoolean(isSorted)) { - context = iteratee; - iteratee = isSorted; - isSorted = false; + has: function (obj, keys) { + if (BI.isArray(keys)) { + if (keys.length === 0) { + return false; } - iteratee && (iteratee = traverse(iteratee, context)); - return BI._.uniq.call(BI._, array, isSorted, iteratee, context); - } - }); - - // 对象相关方法 - BI._.each(["keys", "allKeys", "values", "pairs", "invert", "create", "functions", "extend", "extendOwn", - "defaults", "clone", "property", "propertyOf", "matcher", "isEqual", "isMatch", "isEmpty", - "isElement", "isNumber", "isString", "isArray", "isObject", "isPlainObject", "isArguments", "isFunction", "isFinite", - "isBoolean", "isDate", "isRegExp", "isError", "isNaN", "isUndefined", "zipObject", "cloneDeep"], function (name) { - BI[name] = _apply(name); - }); - BI._.each(["mapObject", "findKey", "pick", "omit", "tap"], function (name) { - BI[name] = _applyFunc(name); - }); - BI._.extend(BI, { - - inherit: function (sp, overrides) { - var sb = function () { - return sp.apply(this, arguments); - }; - var F = function () { - }, spp = sp.prototype; - F.prototype = spp; - sb.prototype = new F(); - sb.superclass = spp; - BI._.extend(sb.prototype, overrides, { - superclass: sp + return BI.every(keys, function (i, key) { + return BI._.has(obj, key); }); - return sb; - }, - - init: function () { - // 先把准备环境准备好 - while (BI.prepares && BI.prepares.length > 0) { - BI.prepares.shift()(); - } - while (_global.___fineuiExposedFunction && _global.___fineuiExposedFunction.length > 0) { - _global.___fineuiExposedFunction.shift()(); + } + return BI._.has.apply(BI._, arguments); + }, + + freeze: function (value) { + // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError + // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 + if (Object.freeze && BI.isObject(value)) { + return Object.freeze(value); + } + return value; + }, + + // 数字和字符串可以作为key + isKey: function (key) { + return BI.isNumber(key) || (BI.isString(key) && key.length > 0); + }, + + // 忽略大小写的等于 + isCapitalEqual: function (a, b) { + a = BI.isNull(a) ? a : ("" + a).toLowerCase(); + b = BI.isNull(b) ? b : ("" + b).toLowerCase(); + return BI.isEqual(a, b); + }, + + isWidthOrHeight: function (w) { + if (typeof w === "number") { + return w >= 0; + } else if (typeof w === "string") { + return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); + } + }, + + isNotNull: function (obj) { + return !BI.isNull(obj); + }, + + isNull: function (obj) { + return typeof obj === "undefined" || obj === null; + }, + + isEmptyArray: function (arr) { + return BI.isArray(arr) && BI.isEmpty(arr); + }, + + isNotEmptyArray: function (arr) { + return BI.isArray(arr) && !BI.isEmpty(arr); + }, + + isEmptyObject: function (obj) { + return BI.isEqual(obj, {}); + }, + + isNotEmptyObject: function (obj) { + return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); + }, + + isEmptyString: function (obj) { + return BI.isString(obj) && obj.length === 0; + }, + + isNotEmptyString: function (obj) { + return BI.isString(obj) && !BI.isEmptyString(obj); + }, + + isWindow: function (obj) { + return obj != null && obj == obj.window; + }, + + isPromise: function (obj) { + return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); + } +}); + +// deep方法 +BI._.extend(BI, { + deepClone: BI._.cloneDeep, + deepExtend: BI._.merge, + + isDeepMatch: function (object, attrs) { + var keys = BI.keys(attrs), length = keys.length; + if (object == null) { + return !length; + } + var obj = Object(object); + for (var i = 0; i < length; i++) { + var key = keys[i]; + if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { + return false; } - BI.initialized = true; - }, - - has: function (obj, keys) { - if (BI.isArray(keys)) { - if (keys.length === 0) { - return false; + } + return true; + }, + + contains: function (obj, target, fromIndex) { + if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); + return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; + }, + + deepContains: function (obj, copy) { + if (BI.isObject(copy)) { + return BI.any(obj, function (i, v) { + if (BI.isEqual(v, copy)) { + return true; } - return BI.every(keys, function (i, key) { - return BI._.has(obj, key); - }); - } - return BI._.has.apply(BI._, arguments); - }, - - freeze: function (value) { - // 在ES5中,如果这个方法的参数不是一个对象(一个原始值),那么它会导致 TypeError - // 在ES2015中,非对象参数将被视为要被冻结的普通对象,并被简单地返回 - if (Object.freeze && BI.isObject(value)) { - return Object.freeze(value); - } - return value; - }, - - // 数字和字符串可以作为key - isKey: function (key) { - return BI.isNumber(key) || (BI.isString(key) && key.length > 0); - }, - - // 忽略大小写的等于 - isCapitalEqual: function (a, b) { - a = BI.isNull(a) ? a : ("" + a).toLowerCase(); - b = BI.isNull(b) ? b : ("" + b).toLowerCase(); - return BI.isEqual(a, b); - }, - - isWidthOrHeight: function (w) { - if (typeof w === "number") { - return w >= 0; - } else if (typeof w === "string") { - return /^\d{1,3}(\.\d)?%$/.test(w) || w === "auto" || /^\d+(\.\d+)?px$/.test(w) || /^calc/.test(w); - } - }, - - isNotNull: function (obj) { - return !BI.isNull(obj); - }, - - isNull: function (obj) { - return typeof obj === "undefined" || obj === null; - }, - - isEmptyArray: function (arr) { - return BI.isArray(arr) && BI.isEmpty(arr); - }, - - isNotEmptyArray: function (arr) { - return BI.isArray(arr) && !BI.isEmpty(arr); - }, - - isEmptyObject: function (obj) { - return BI.isEqual(obj, {}); - }, - - isNotEmptyObject: function (obj) { - return BI.isPlainObject(obj) && !BI.isEmptyObject(obj); - }, - - isEmptyString: function (obj) { - return BI.isString(obj) && obj.length === 0; - }, - - isNotEmptyString: function (obj) { - return BI.isString(obj) && !BI.isEmptyString(obj); - }, - - isWindow: function (obj) { - return obj != null && obj == obj.window; - }, - - isPromise: function (obj) { - return !!obj && (BI.isObject(obj) || BI.isFunction(obj)) && BI.isFunction(obj.then); + }); } - }); - - // deep方法 - BI._.extend(BI, { - deepClone: BI._.cloneDeep, - deepExtend: BI._.merge, + return BI.contains(obj, copy); + }, - isDeepMatch: function (object, attrs) { - var keys = BI.keys(attrs), length = keys.length; - if (object == null) { - return !length; - } - var obj = Object(object); - for (var i = 0; i < length; i++) { - var key = keys[i]; - if (!BI.isEqual(attrs[key], obj[key]) || !(key in obj)) { - return false; - } - } - return true; - }, - - contains: function (obj, target, fromIndex) { - if (!BI._.isArrayLike(obj)) obj = BI._.values(obj); - return BI._.indexOf(obj, target, typeof fromIndex === "number" && fromIndex) >= 0; - }, - - deepContains: function (obj, copy) { - if (BI.isObject(copy)) { - return BI.any(obj, function (i, v) { - if (BI.isEqual(v, copy)) { - return true; - } - }); + deepIndexOf: function (obj, target) { + for (var i = 0; i < obj.length; i++) { + if (BI.isEqual(target, obj[i])) { + return i; } - return BI.contains(obj, copy); - }, - - deepIndexOf: function (obj, target) { - for (var i = 0; i < obj.length; i++) { + } + return -1; + }, + + deepRemove: function (obj, target) { + var done = false; + var i; + if (BI.isArray(obj)) { + for (i = 0; i < obj.length; i++) { if (BI.isEqual(target, obj[i])) { - return i; - } - } - return -1; - }, - - deepRemove: function (obj, target) { - var done = false; - var i; - if (BI.isArray(obj)) { - for (i = 0; i < obj.length; i++) { - if (BI.isEqual(target, obj[i])) { - obj.splice(i--, 1); - done = true; - } - } - } else { - BI.each(obj, function (i, v) { - if (BI.isEqual(target, obj[i])) { - delete obj[i]; - done = true; - } - }); - } - return done; - }, - - deepWithout: function (obj, target) { - if (BI.isArray(obj)) { - var result = []; - for (var i = 0; i < obj.length; i++) { - if (!BI.isEqual(target, obj[i])) { - result.push(obj[i]); - } + obj.splice(i--, 1); + done = true; } - return result; } - var result = {}; + } else { BI.each(obj, function (i, v) { - if (!BI.isEqual(target, obj[i])) { - result[i] = v; - } - }); - return result; - - }, - - deepUnique: function (array) { - var result = []; - BI.each(array, function (i, item) { - if (!BI.deepContains(result, item)) { - result.push(item); + if (BI.isEqual(target, obj[i])) { + delete obj[i]; + done = true; } }); - return result; - }, + } + return done; + }, - // 比较两个对象得出不一样的key值 - deepDiff: function (object, other) { - object || (object = {}); - other || (other = {}); + deepWithout: function (obj, target) { + if (BI.isArray(obj)) { var result = []; - var used = []; - for (var b in object) { - if (this.has(object, b)) { - if (!this.isEqual(object[b], other[b])) { - result.push(b); - } - used.push(b); + for (var i = 0; i < obj.length; i++) { + if (!BI.isEqual(target, obj[i])) { + result.push(obj[i]); } } - for (var b in other) { - if (this.has(other, b) && !BI.contains(used, b)) { + return result; + } + var result = {}; + BI.each(obj, function (i, v) { + if (!BI.isEqual(target, obj[i])) { + result[i] = v; + } + }); + return result; + + }, + + deepUnique: function (array) { + var result = []; + BI.each(array, function (i, item) { + if (!BI.deepContains(result, item)) { + result.push(item); + } + }); + return result; + }, + + // 比较两个对象得出不一样的key值 + deepDiff: function (object, other) { + object || (object = {}); + other || (other = {}); + var result = []; + var used = []; + for (var b in object) { + if (this.has(object, b)) { + if (!this.isEqual(object[b], other[b])) { result.push(b); } + used.push(b); + } + } + for (var b in other) { + if (this.has(other, b) && !BI.contains(used, b)) { + result.push(b); } - return result; } - }); + return result; + } +}); + +// 通用方法 +BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { + BI[name] = function () { + return BI._[name].apply(BI._, arguments); + }; +}); - // 通用方法 - BI._.each(["uniqueId", "result", "chain", "iteratee", "escape", "unescape", "before", "after", "chunk"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; - }); +// 事件相关方法 +BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { + BI[name] = function () { + return BI._[name].apply(BI._, arguments); + }; +}); - // 事件相关方法 - BI._.each(["bind", "once", "partial", "debounce", "throttle", "delay", "defer", "wrap"], function (name) { - BI[name] = function () { - return BI._[name].apply(BI._, arguments); - }; - }); - - BI._.extend(BI, { - nextTick: (function () { - var callbacks = []; - var pending = false; - var timerFunc = void 0; - - function nextTickHandler() { - pending = false; - var copies = callbacks.slice(0); - callbacks.length = 0; - for (var i = 0; i < copies.length; i++) { - copies[i](); - } - } +BI._.extend(BI, { + nextTick: (function () { + var callbacks = []; + var pending = false; + var timerFunc = void 0; - if (typeof Promise !== "undefined") { - var p = Promise.resolve(); - timerFunc = function timerFunc() { - p.then(nextTickHandler); - }; - } else if (typeof MutationObserver !== "undefined") { - var counter = 1; - var observer = new MutationObserver(nextTickHandler); - var textNode = document.createTextNode(String(counter)); - observer.observe(textNode, { - characterData: true - }); - timerFunc = function timerFunc() { - counter = (counter + 1) % 2; - textNode.data = String(counter); - }; - } else if (typeof setImmediate !== "undefined") { - timerFunc = function timerFunc() { - setImmediate(nextTickHandler); - }; - } else { - // Fallback to setTimeout. - timerFunc = function timerFunc() { - setTimeout(nextTickHandler, 0); - }; + function nextTickHandler() { + pending = false; + var copies = callbacks.slice(0); + callbacks.length = 0; + for (var i = 0; i < copies.length; i++) { + copies[i](); } + } - return function queueNextTick(cb) { - var _resolve = void 0; - var args = [].slice.call(arguments, 1); - callbacks.push(function () { - if (cb) { - try { - cb.apply(null, args); - } catch (e) { - console.error(e); - } - } else if (_resolve) { - _resolve.apply(null, args); + if (typeof Promise !== "undefined") { + var p = Promise.resolve(); + timerFunc = function timerFunc() { + p.then(nextTickHandler); + }; + } else if (typeof MutationObserver !== "undefined") { + var counter = 1; + var observer = new MutationObserver(nextTickHandler); + var textNode = document.createTextNode(String(counter)); + observer.observe(textNode, { + characterData: true + }); + timerFunc = function timerFunc() { + counter = (counter + 1) % 2; + textNode.data = String(counter); + }; + } else if (typeof setImmediate !== "undefined") { + timerFunc = function timerFunc() { + setImmediate(nextTickHandler); + }; + } else { + // Fallback to setTimeout. + timerFunc = function timerFunc() { + setTimeout(nextTickHandler, 0); + }; + } + + return function queueNextTick(cb) { + var _resolve = void 0; + var args = [].slice.call(arguments, 1); + callbacks.push(function () { + if (cb) { + try { + cb.apply(null, args); + } catch (e) { + console.error(e); } - }); - if (!pending) { - pending = true; - timerFunc(); + } else if (_resolve) { + _resolve.apply(null, args); } - // $flow-disable-line - if (!cb && typeof Promise !== 'undefined') { - return new Promise(function (resolve, reject) { - _resolve = resolve; - }); - } - }; - })() - }); - - // 数字相关方法 - BI._.each(["random"], function (name) { - BI[name] = _apply(name); - }); - BI._.extend(BI, { - - parseInt: function (number) { - var radix = 10; - if (/^0x/g.test(number)) { - radix = 16; - } - try { - return parseInt(number, radix); - } catch (e) { - throw new Error(number + "parse int error"); - return NaN; - } - }, - - parseSafeInt: function (value) { - var MAX_SAFE_INTEGER = 9007199254740991; - return value - ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); - }, - - parseFloat: function (number) { - try { - return parseFloat(number); - } catch (e) { - throw new Error(number + "parse float error"); - return NaN; + }); + if (!pending) { + pending = true; + timerFunc(); + } + // $flow-disable-line + if (!cb && typeof Promise !== 'undefined') { + return new Promise(function (resolve, reject) { + _resolve = resolve; + }); } - }, + }; + })() +}); + +// 数字相关方法 +BI._.each(["random"], function (name) { + BI[name] = _apply(name); +}); +BI._.extend(BI, { + + parseInt: function (number) { + var radix = 10; + if (/^0x/g.test(number)) { + radix = 16; + } + try { + return parseInt(number, radix); + } catch (e) { + throw new Error(number + "parse int error"); + return NaN; + } + }, + + parseSafeInt: function (value) { + var MAX_SAFE_INTEGER = 9007199254740991; + return value + ? this.clamp(this.parseInt(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + }, + + parseFloat: function (number) { + try { + return parseFloat(number); + } catch (e) { + throw new Error(number + "parse float error"); + return NaN; + } + }, - isNaturalNumber: function (number) { - if (/^\d+$/.test(number)) { - return true; - } - return false; - }, + isNaturalNumber: function (number) { + if (/^\d+$/.test(number)) { + return true; + } + return false; + }, - isPositiveInteger: function (number) { - if (/^\+?[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, + isPositiveInteger: function (number) { + if (/^\+?[1-9][0-9]*$/.test(number)) { + return true; + } + return false; + }, - isNegativeInteger: function (number) { - if (/^\-[1-9][0-9]*$/.test(number)) { - return true; - } - return false; - }, + isNegativeInteger: function (number) { + if (/^\-[1-9][0-9]*$/.test(number)) { + return true; + } + return false; + }, - isInteger: function (number) { - if (/^\-?\d+$/.test(number)) { - return true; - } - return false; - }, + isInteger: function (number) { + if (/^\-?\d+$/.test(number)) { + return true; + } + return false; + }, - isNumeric: function (number) { - return !isNaN(parseFloat(number)) && isFinite(number); - }, + isNumeric: function (number) { + return !isNaN(parseFloat(number)) && isFinite(number); + }, - isFloat: function (number) { - if (/^([+-]?)\d*\.\d+$/.test(number)) { - return true; - } - return false; - }, + isFloat: function (number) { + if (/^([+-]?)\d*\.\d+$/.test(number)) { + return true; + } + return false; + }, - isOdd: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 1; - }, + isOdd: function (number) { + if (!BI.isInteger(number)) { + return false; + } + return (number & 1) === 1; + }, - isEven: function (number) { - if (!BI.isInteger(number)) { - return false; - } - return (number & 1) === 0; - }, - - sum: function (array, iteratee, context) { - var sum = 0; - BI.each(array, function (i, item) { - if (iteratee) { - sum += Number(iteratee.apply(context, [i, item])); - } else { - sum += Number(item); - } - }); - return sum; - }, - - average: function (array, iteratee, context) { - var sum = BI.sum(array, iteratee, context); - return sum / array.length; - } - }); - - // 字符串相关方法 - BI._.extend(BI, { - trim: function () { - return BI._.trim.apply(BI._, arguments); - }, - - toUpperCase: function (string) { - return (string + "").toLocaleUpperCase(); - }, - - toLowerCase: function (string) { - return (string + "").toLocaleLowerCase(); - }, - - isEndWithBlank: function (string) { - return /(\s|\u00A0)$/.test(string); - }, - - isLiteral: function (exp) { - var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; - return literalValueRE.test(exp); - }, - - stripQuotes: function (str) { - var a = str.charCodeAt(0); - var b = str.charCodeAt(str.length - 1); - return a === b && (a === 0x22 || a === 0x27) - ? str.slice(1, -1) - : str; - }, - - // background-color => backgroundColor - camelize: function (str) { - return str.replace(/-(.)/g, function (_, character) { - return character.toUpperCase(); - }); - }, - - // backgroundColor => background-color - hyphenate: function (str) { - return str.replace(/([A-Z])/g, "-$1").toLowerCase(); - }, - - isNotEmptyString: function (str) { - return BI.isString(str) && !BI.isEmpty(str); - }, - - isEmptyString: function (str) { - return BI.isString(str) && BI.isEmpty(str); - }, - - /** - * 通用加密方法 - */ - encrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesEncrypt(text, key); - } - }, - - /** - * 通用解密方法 - * @param type 解密方式 - * @param text 文本 - * @param key 种子 - * @return {*} - */ - decrypt: function (type, text, key) { - switch (type) { - case BI.CRYPT_TYPE.AES: - default: - return BI.aesDecrypt(text, key); - } - }, - - /** - * 对字符串中的'和\做编码处理 - * @static - * @param {String} string 要做编码处理的字符串 - * @return {String} 编码后的字符串 - */ - escape: function (string) { - return string.replace(/('|\\)/g, "\\$1"); - }, - - /** - * 让字符串通过指定字符做补齐的函数 - * - * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' - * - * @static - * @param {String} val 原始值 - * @param {Number} size 总共需要的位数 - * @param {String} ch 用于补齐的字符 - * @return {String} 补齐后的字符串 - */ - leftPad: function (val, size, ch) { - var result = String(val); - if (!ch) { - ch = " "; - } - while (result.length < size) { - result = ch + result; - } - return result.toString(); - }, - - /** - * 对字符串做替换的函数 - * - * var cls = 'my-class', text = 'Some text'; - * var res = BI.format('
{1}
', cls, text); - * //res的值为:'
Some text
'; - * - * @static - * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... - * @return {String} 做了替换后的字符串 - */ - format: function (format) { - var args = Array.prototype.slice.call(arguments, 1); - return format.replace(/\{(\d+)\}/g, function (m, i) { - return args[i]; - }); + isEven: function (number) { + if (!BI.isInteger(number)) { + return false; } - }); - - // 日期相关方法 - BI._.extend(BI, { - /** - * 是否是闰年 - * @param year - * @returns {boolean} - */ - isLeapYear: function (year) { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; - }, - - /** - * 检测是否在有效期 - * - * @param YY 年 - * @param MM 月 - * @param DD 日 - * @param minDate '1900-01-01' - * @param maxDate '2099-12-31' - * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 - */ - checkDateVoid: function (YY, MM, DD, minDate, maxDate) { - var back = []; - YY = YY | 0; - MM = MM | 0; - DD = DD | 0; - minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; - maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; - if (YY < minDate[0]) { - back = ["y"]; - } else if (YY > maxDate[0]) { - back = ["y", 1]; - } else if (YY >= minDate[0] && YY <= maxDate[0]) { - if (YY == minDate[0]) { - if (MM < minDate[1]) { - back = ["m"]; - } else if (MM == minDate[1]) { - if (DD < minDate[2]) { - back = ["d"]; - } + return (number & 1) === 0; + }, + + sum: function (array, iteratee, context) { + var sum = 0; + BI.each(array, function (i, item) { + if (iteratee) { + sum += Number(iteratee.apply(context, [i, item])); + } else { + sum += Number(item); + } + }); + return sum; + }, + + average: function (array, iteratee, context) { + var sum = BI.sum(array, iteratee, context); + return sum / array.length; + } +}); + +// 字符串相关方法 +BI._.extend(BI, { + trim: function () { + return BI._.trim.apply(BI._, arguments); + }, + + toUpperCase: function (string) { + return (string + "").toLocaleUpperCase(); + }, + + toLowerCase: function (string) { + return (string + "").toLocaleLowerCase(); + }, + + isEndWithBlank: function (string) { + return /(\s|\u00A0)$/.test(string); + }, + + isLiteral: function (exp) { + var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; + return literalValueRE.test(exp); + }, + + stripQuotes: function (str) { + var a = str.charCodeAt(0); + var b = str.charCodeAt(str.length - 1); + return a === b && (a === 0x22 || a === 0x27) + ? str.slice(1, -1) + : str; + }, + + // background-color => backgroundColor + camelize: function (str) { + return str.replace(/-(.)/g, function (_, character) { + return character.toUpperCase(); + }); + }, + + // backgroundColor => background-color + hyphenate: function (str) { + return str.replace(/([A-Z])/g, "-$1").toLowerCase(); + }, + + isNotEmptyString: function (str) { + return BI.isString(str) && !BI.isEmpty(str); + }, + + isEmptyString: function (str) { + return BI.isString(str) && BI.isEmpty(str); + }, + + /** + * 通用加密方法 + */ + encrypt: function (type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesEncrypt(text, key); + } + }, + + /** + * 通用解密方法 + * @param type 解密方式 + * @param text 文本 + * @param key 种子 + * @return {*} + */ + decrypt: function (type, text, key) { + switch (type) { + case BI.CRYPT_TYPE.AES: + default: + return BI.aesDecrypt(text, key); + } + }, + + /** + * 对字符串中的'和\做编码处理 + * @static + * @param {String} string 要做编码处理的字符串 + * @return {String} 编码后的字符串 + */ + escape: function (string) { + return string.replace(/('|\\)/g, "\\$1"); + }, + + /** + * 让字符串通过指定字符做补齐的函数 + * + * var s = BI.leftPad('123', 5, '0');//s的值为:'00123' + * + * @static + * @param {String} val 原始值 + * @param {Number} size 总共需要的位数 + * @param {String} ch 用于补齐的字符 + * @return {String} 补齐后的字符串 + */ + leftPad: function (val, size, ch) { + var result = String(val); + if (!ch) { + ch = " "; + } + while (result.length < size) { + result = ch + result; + } + return result.toString(); + }, + + /** + * 对字符串做替换的函数 + * + * var cls = 'my-class', text = 'Some text'; + * var res = BI.format('
{1}
', cls, text); + * //res的值为:'
Some text
'; + * + * @static + * @param {String} format 要做替换的字符串,替换字符串1,替换字符串2... + * @return {String} 做了替换后的字符串 + */ + format: function (format) { + var args = Array.prototype.slice.call(arguments, 1); + return format.replace(/\{(\d+)\}/g, function (m, i) { + return args[i]; + }); + } +}); + +// 日期相关方法 +BI._.extend(BI, { + /** + * 是否是闰年 + * @param year + * @returns {boolean} + */ + isLeapYear: function (year) { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + }, + + /** + * 检测是否在有效期 + * + * @param YY 年 + * @param MM 月 + * @param DD 日 + * @param minDate '1900-01-01' + * @param maxDate '2099-12-31' + * @returns {Array} 若无效返回无效状态,数组第一位为无效属性,第二位缺省为超下限,1为超上限 + */ + checkDateVoid: function (YY, MM, DD, minDate, maxDate) { + var back = []; + YY = YY | 0; + MM = MM | 0; + DD = DD | 0; + minDate = BI.isString(minDate) ? minDate.match(/\d+/g) : minDate; + maxDate = BI.isString(maxDate) ? maxDate.match(/\d+/g) : maxDate; + if (YY < minDate[0]) { + back = ["y"]; + } else if (YY > maxDate[0]) { + back = ["y", 1]; + } else if (YY >= minDate[0] && YY <= maxDate[0]) { + if (YY == minDate[0]) { + if (MM < minDate[1]) { + back = ["m"]; + } else if (MM == minDate[1]) { + if (DD < minDate[2]) { + back = ["d"]; } } - if (YY == maxDate[0]) { - if (MM > maxDate[1]) { - back = ["m", 1]; - } else if (MM == maxDate[1]) { - if (DD > maxDate[2]) { - back = ["d", 1]; - } + } + if (YY == maxDate[0]) { + if (MM > maxDate[1]) { + back = ["m", 1]; + } else if (MM == maxDate[1]) { + if (DD > maxDate[2]) { + back = ["d", 1]; } } } - return back; - }, - - checkDateLegal: function (str) { - var ar = str.match(/\d+/g); - var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; - if (ar.length <= 1) { - return true; - } - if (ar.length <= 2) { - return MM >= 1 && MM <= 12; - } - var MD = BI.Date._MD.slice(0); - MD[1] = BI.isLeapYear(YY) ? 29 : 28; - return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; - }, - - parseDateTime: function (str, fmt) { - var today = BI.getDate(); - var y = 0; - var m = 0; - var d = 1; - // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 - var a = str.split(/\W+/); - if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { - var yearlength = 4; - var otherlength = 2; - a[0] = str.substring(0, yearlength); - a[1] = str.substring(yearlength, yearlength + otherlength); - a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); - } - var b = fmt.match(/%./g); - var i = 0, j = 0; - var hr = 0; - var min = 0; - var sec = 0; - for (i = 0; i < a.length; ++i) { - switch (b[i]) { - case "%d": - case "%e": - d = parseInt(a[i], 10); - break; - - case "%X": - m = parseInt(a[i], 10) - 1; - break; - case "%x": - m = parseInt(a[i], 10) - 1; - break; + } + return back; + }, - case "%Y": - case "%y": - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - break; + checkDateLegal: function (str) { + var ar = str.match(/\d+/g); + var YY = ar[0] | 0, MM = ar[1] | 0, DD = ar[2] | 0; + if (ar.length <= 1) { + return true; + } + if (ar.length <= 2) { + return MM >= 1 && MM <= 12; + } + var MD = BI.Date._MD.slice(0); + MD[1] = BI.isLeapYear(YY) ? 29 : 28; + return MM >= 1 && MM <= 12 && DD <= MD[MM - 1]; + }, + + parseDateTime: function (str, fmt) { + var today = BI.getDate(); + var y = 0; + var m = 0; + var d = 1; + // wei : 对于fmt为‘YYYYMM’或者‘YYYYMMdd’的格式,str的值为类似'201111'的形式,因为年月之间没有分隔符,所以正则表达式分割无效,导致bug7376。 + var a = str.split(/\W+/); + if (fmt.toLowerCase() == "%y%x" || fmt.toLowerCase() == "%y%x%d") { + var yearlength = 4; + var otherlength = 2; + a[0] = str.substring(0, yearlength); + a[1] = str.substring(yearlength, yearlength + otherlength); + a[2] = str.substring(yearlength + otherlength, yearlength + otherlength * 2); + } + var b = fmt.match(/%./g); + var i = 0, j = 0; + var hr = 0; + var min = 0; + var sec = 0; + for (i = 0; i < a.length; ++i) { + switch (b[i]) { + case "%d": + case "%e": + d = parseInt(a[i], 10); + break; - case "%b": - case "%B": - for (j = 0; j < 12; ++j) { - if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - m = j; - break; - } - } - break; + case "%X": + m = parseInt(a[i], 10) - 1; + break; + case "%x": + m = parseInt(a[i], 10) - 1; + break; - case "%H": - case "%I": - case "%k": - case "%l": - hr = parseInt(a[i], 10); - break; + case "%Y": + case "%y": + y = parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + break; - case "%P": - case "%p": - if (/pm/i.test(a[i]) && hr < 12) { - hr += 12; - } else if (/am/i.test(a[i]) && hr >= 12) { - hr -= 12; - } - break; - case "%Q": - case "%q": - m = (parseInt(a[i], 10) - 1) * 3; - break; - case "%M": - min = parseInt(a[i], 10); - break; - case "%S": - sec = parseInt(a[i], 10); - break; - } - } - // if (!a[i]) { - // continue; - // } - if (isNaN(y)) { - y = today.getFullYear(); - } - if (isNaN(m)) { - m = today.getMonth(); - } - if (isNaN(d)) { - d = today.getDate(); - } - if (isNaN(hr)) { - hr = today.getHours(); - } - if (isNaN(min)) { - min = today.getMinutes(); - } - if (isNaN(sec)) { - sec = today.getSeconds(); - } - if (y != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - y = 0; - m = -1; - d = 0; - for (i = 0; i < a.length; ++i) { - if (a[i].search(/[a-zA-Z]+/) != -1) { - var t = -1; + case "%b": + case "%B": for (j = 0; j < 12; ++j) { if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { - t = j; + m = j; break; } } - if (t != -1) { - if (m != -1) { - d = m + 1; - } - m = t; - } - } else if (parseInt(a[i], 10) <= 12 && m == -1) { - m = a[i] - 1; - } else if (parseInt(a[i], 10) > 31 && y == 0) { - y = parseInt(a[i], 10); - (y < 100) && (y += (y > 29) ? 1900 : 2000); - } else if (d == 0) { - d = a[i]; - } - } - if (y == 0) { - y = today.getFullYear(); - } - if (m === -1) { - m = today.getMonth(); - } - if (m != -1 && d != 0) { - return BI.getDate(y, m, d, hr, min, sec); - } - return today; - }, - - getDate: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); - break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); - break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); - break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); break; - default: - dt = new Date(); - break; - } - if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { - var localTime = dt.getTime(); - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 - var utc = localTime + localOffset; // utc即GMT时间标准时区 - return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); - } - return dt; - - }, - - getTime: function () { - var length = arguments.length; - var args = arguments; - var dt; - switch (length) { - // new Date() - case 0: - dt = new Date(); - break; - // new Date(long) - case 1: - dt = new Date(args[0]); - break; - // new Date(year, month) - case 2: - dt = new Date(args[0], args[1]); - break; - // new Date(year, month, day) - case 3: - dt = new Date(args[0], args[1], args[2]); - break; - // new Date(year, month, day, hour) - case 4: - dt = new Date(args[0], args[1], args[2], args[3]); + + case "%H": + case "%I": + case "%k": + case "%l": + hr = parseInt(a[i], 10); break; - // new Date(year, month, day, hour, minute) - case 5: - dt = new Date(args[0], args[1], args[2], args[3], args[4]); + + case "%P": + case "%p": + if (/pm/i.test(a[i]) && hr < 12) { + hr += 12; + } else if (/am/i.test(a[i]) && hr >= 12) { + hr -= 12; + } break; - // new Date(year, month, day, hour, minute, second) - case 6: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + case "%Q": + case "%q": + m = (parseInt(a[i], 10) - 1) * 3; break; - // new Date(year, month, day, hour, minute, second, millisecond) - case 7: - dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + case "%M": + min = parseInt(a[i], 10); break; - default: - dt = new Date(); + case "%S": + sec = parseInt(a[i], 10); break; } - if (BI.isNotNull(BI.timeZone)) { - // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 - return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + // if (!a[i]) { + // continue; + // } + if (isNaN(y)) { + y = today.getFullYear(); + } + if (isNaN(m)) { + m = today.getMonth(); + } + if (isNaN(d)) { + d = today.getDate(); + } + if (isNaN(hr)) { + hr = today.getHours(); + } + if (isNaN(min)) { + min = today.getMinutes(); + } + if (isNaN(sec)) { + sec = today.getSeconds(); + } + if (y != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + y = 0; + m = -1; + d = 0; + for (i = 0; i < a.length; ++i) { + if (a[i].search(/[a-zA-Z]+/) != -1) { + var t = -1; + for (j = 0; j < 12; ++j) { + if (BI.getMonthName(j).substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { + t = j; + break; + } + } + if (t != -1) { + if (m != -1) { + d = m + 1; + } + m = t; + } + } else if (parseInt(a[i], 10) <= 12 && m == -1) { + m = a[i] - 1; + } else if (parseInt(a[i], 10) > 31 && y == 0) { + y = parseInt(a[i], 10); + (y < 100) && (y += (y > 29) ? 1900 : 2000); + } else if (d == 0) { + d = a[i]; } - return dt.getTime(); - } - }); -})(); + if (y == 0) { + y = today.getFullYear(); + } + if (m === -1) { + m = today.getMonth(); + } + if (m != -1 && d != 0) { + return BI.getDate(y, m, d, hr, min, sec); + } + return today; + }, + + getDate: function () { + var length = arguments.length; + var args = arguments; + var dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (BI.isNotNull(BI.timeZone) && (arguments.length === 0 || (arguments.length === 1 && BI.isNumber(arguments[0])))) { + var localTime = dt.getTime(); + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + var localOffset = dt.getTimezoneOffset() * 60000; // 获得当地时间偏移的毫秒数 + var utc = localTime + localOffset; // utc即GMT时间标准时区 + return new Date(utc + BI.timeZone);// + Pool.timeZone.offset); + } + return dt; + + }, + + getTime: function () { + var length = arguments.length; + var args = arguments; + var dt; + switch (length) { + // new Date() + case 0: + dt = new Date(); + break; + // new Date(long) + case 1: + dt = new Date(args[0]); + break; + // new Date(year, month) + case 2: + dt = new Date(args[0], args[1]); + break; + // new Date(year, month, day) + case 3: + dt = new Date(args[0], args[1], args[2]); + break; + // new Date(year, month, day, hour) + case 4: + dt = new Date(args[0], args[1], args[2], args[3]); + break; + // new Date(year, month, day, hour, minute) + case 5: + dt = new Date(args[0], args[1], args[2], args[3], args[4]); + break; + // new Date(year, month, day, hour, minute, second) + case 6: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5]); + break; + // new Date(year, month, day, hour, minute, second, millisecond) + case 7: + dt = new Date(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + break; + default: + dt = new Date(); + break; + } + if (BI.isNotNull(BI.timeZone)) { + // BI-33791 1901年以前的东8区标准是GMT+0805, 统一无论是什么时间,都以整的0800这样的为基准 + return dt.getTime() - BI.timeZone - new Date().getTimezoneOffset() * 60000; + } + return dt.getTime(); + + } +}); + +// TODO: 暂时先直接export全部,下一步拆function +export default BI; \ No newline at end of file diff --git a/src/core/3.ob.js b/src/core/3.ob.js index 100fcac17..f6e9396de 100644 --- a/src/core/3.ob.js +++ b/src/core/3.ob.js @@ -1,220 +1,221 @@ -!(function () { - function extend() { - var target = arguments[0] || {}, length = arguments.length, i = 1, options, name, src, copy; - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) { - continue; - } +import BI from "./2.base"; + +function extend() { + let target = arguments[0] || {}, length = arguments.length, i = 1, name, copy; + for (; i < length; i++) { + // Only deal with non-null/undefined values + const options = arguments[i]; + if (options !== null) { + // Extend the base object + for (name in options) { + copy = options[name]; + + // Prevent never-ending loop + if (target === copy) { + continue; + } - if (copy !== undefined) { - target[name] = copy; - } + + if (copy !== undefined) { + target[name] = copy; } } } - return target; } - /** - * 客户端观察者,主要处理事件的添加、删除、执行等 - * @class BI.OB - * @abstract - */ - var OB = function (config) { - this._constructor(config); - }; - BI._.extend(OB.prototype, { - props: {}, + return target; +} - init: null, +export default class OB { + // props = {}; - destroyed: null, + // init = null; - _constructor: function (config) { - this._initProps(config); - this._init(); - this._initRef(); - }, + // destroyed = null; - _defaultConfig: function (config) { - return {}; - }, + constructor(config) { + this._constructor(config); + } + + _constructor(config) { + this._initProps(config); + this._init(); + this._initRef(); + } - _initProps: function (config) { - var props = this.props; - if (BI.isFunction(this.props)) { - props = this.props(config); - } - var defaultProps = extend(this._defaultConfig(config), props); - var modifiedDefaultProps = (config && config.type && BI.OB.configFunctions[config.type + ".props"]) ? BI.reduce(BI.OB.configFunctions[config.type + ".props"], function (value, conf, index) { - return extend(conf, value.fn(defaultProps, config, value.opt)); - }, {}) : null; - this.options = extend(defaultProps, modifiedDefaultProps, config); - }, - - _init: function () { - this._initListeners(); - this.init && this.init(); - }, - - _initListeners: function () { - var self = this; - if (this.options.listeners != null) { - BI._.each(this.options.listeners, function (lis, eventName) { - if (BI._.isFunction(lis)) { - self.on(eventName, lis); - return; - } - if (BI._.isArray(lis)) { - BI._.each(lis, function (l) { - self.on(eventName, l); - }); - return; - } - (lis.target ? lis.target : self)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, self)); - }); - delete this.options.listeners; - } - }, + _defaultConfig(config) { + return {}; + } - // 获得一个当前对象的引用 - _initRef: function () { - var o = this.options; - if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; - } - if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; - } - }, - - //释放当前对象 - _purgeRef: function () { - var o = this.options; - if (o.__ref) { - BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; - o.__ref = null; - } - if (o.ref) { - BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; - o.ref = null; - } - }, + _initProps(config) { + let props = this.props; + if (BI.isFunction(this.props)) { + props = this.props(config); + } + const defaultProps = extend(this._defaultConfig(config), props); + const modifiedDefaultProps = (config && config.type && OB.configFunctions[config.type + ".props"]) ? BI.reduce(OB.configFunctions[config.type + ".props"], function (value, conf, index) { + return extend(conf, value.fn(defaultProps, config, value.opt)); + }, {}) : null; + this.options = extend(defaultProps, modifiedDefaultProps, config); + } - _getEvents: function () { - if (!BI._.isObject(this.events)) { - this.events = {}; - } - return this.events; - }, - - /** - * 给观察者绑定一个事件 - * @param {String} eventName 事件的名字 - * @param {Function} fn 事件对应的执行函数 - */ - on: function (eventName, fn) { - var self = this; - eventName = eventName.toLowerCase(); - var fns = this._getEvents()[eventName]; - if (!BI._.isArray(fns)) { - fns = []; - this._getEvents()[eventName] = fns; - } - fns.push(fn); - - return function () { - self.un(eventName, fn); - }; - }, - - /** - * 给观察者绑定一个只执行一次的事件 - * @param {String} eventName 事件的名字 - * @param {Function} fn 事件对应的执行函数 - */ - once: function (eventName, fn) { - var proxy = function () { - fn.apply(this, arguments); - this.un(eventName, proxy); - }; - this.on(eventName, proxy); - }, - - /** - * 解除观察者绑定的指定事件 - * @param {String} eventName 要解除绑定事件的名字 - * @param {Function} fn 事件对应的执行函数,该参数是可选的,没有该参数时,将解除绑定所有同名字的事件 - */ - un: function (eventName, fn) { - eventName = eventName.toLowerCase(); - - /* alex:如果fn是null,就是把eventName上面所有方法都un掉*/ - if (fn == null) { - delete this._getEvents()[eventName]; - } else { - var fns = this._getEvents()[eventName]; - if (BI._.isArray(fns)) { - var newFns = []; - BI._.each(fns, function (ifn) { - if (ifn != fn) { - newFns.push(ifn); - } + _init() { + this._initListeners(); + this.init && this.init(); + } + + _initListeners() { + if (this.options.listeners !== null) { + BI._.each(this.options.listeners, (lis, eventName) => { + if (BI._.isFunction(lis)) { + this.on(eventName, lis); + + return; + } + if (BI._.isArray(lis)) { + BI._.each(lis, (l) => { + this.on(eventName, l); }); - this._getEvents()[eventName] = newFns; + + return; } - } - }, + (lis.target ? lis.target : this)[lis.once ? "once" : "on"](lis.eventName, BI._.bind(lis.action, this)); + }); + delete this.options.listeners; + } + } + + // 获得一个当前对象的引用 + _initRef() { + const o = this.options; + if (o.__ref) { + BI.isFunction(o.__ref) ? o.__ref.call(this, this) : o.__ref.current = this; + } + if (o.ref) { + BI.isFunction(o.ref) ? o.ref.call(this, this) : o.ref.current = this; + } + } + + // 释放当前对象 + _purgeRef() { + const o = this.options; + if (o.__ref) { + BI.isFunction(o.__ref) ? o.__ref.call(null, null) : o.__ref.current = null; + o.__ref = null; + } + if (o.ref) { + BI.isFunction(o.ref) ? o.ref.call(null, null) : o.ref.current = null; + o.ref = null; + } + } - /** - * 清除观察者的所有事件绑定 - */ - purgeListeners: function () { - /* alex:清空events*/ + _getEvents() { + if (!BI._.isObject(this.events)) { this.events = {}; - }, - - /** - * 触发绑定过的事件 - * - * @param {String} eventName 要触发的事件的名字 - * @returns {Boolean} 如果事件函数返回false,则返回false并中断其他同名事件的执行,否则执行所有的同名事件并返回true - */ - fireEvent: function () { - var eventName = arguments[0].toLowerCase(); - var fns = this._getEvents()[eventName]; - if (BI.isArray(fns)) { - if (BI.isArguments(arguments[1])) { - for (var i = 0; i < fns.length; i++) { - if (fns[i].apply(this, arguments[1]) === false) { - return false; - } + } + + return this.events; + } + + /** + * 给观察者绑定一个事件 + * @param {String} eventName 事件的名字 + * @param {Function} fn 事件对应的执行函数 + */ + on(eventName, fn) { + eventName = eventName.toLowerCase(); + let fns = this._getEvents()[eventName]; + if (!BI._.isArray(fns)) { + fns = []; + this._getEvents()[eventName] = fns; + } + fns.push(fn); + + return () => this.un(eventName, fn); + } + + /** + * 给观察者绑定一个只执行一次的事件 + * @param {String} eventName 事件的名字 + * @param {Function} fn 事件对应的执行函数 + */ + once(eventName, fn) { + const proxy = () => { + fn.apply(this, arguments); + this.un(eventName, proxy); + }; + this.on(eventName, proxy); + } + + /** + * 解除观察者绑定的指定事件 + * @param {String} eventName 要解除绑定事件的名字 + * @param {Function} fn 事件对应的执行函数,该参数是可选的,没有该参数时,将解除绑定所有同名字的事件 + */ + un(eventName, fn) { + eventName = eventName.toLowerCase(); + + /* alex:如果fn是null,就是把eventName上面所有方法都un掉*/ + if (fn === null) { + delete this._getEvents()[eventName]; + } else { + const fns = this._getEvents()[eventName]; + if (BI._.isArray(fns)) { + const newFns = []; + BI._.each(fns, function (ifn) { + if (ifn !== fn) { + newFns.push(ifn); + } + }); + this._getEvents()[eventName] = newFns; + } + } + } + + /** + * 清除观察者的所有事件绑定 + */ + purgeListeners() { + /* alex:清空events*/ + this.events = {}; + } + + /** + * 触发绑定过的事件 + * + * @param {String} eventName 要触发的事件的名字 + * @returns {Boolean} 如果事件函数返回false,则返回false并中断其他同名事件的执行,否则执行所有的同名事件并返回true + */ + fireEvent() { + const eventName = arguments[0].toLowerCase(); + const fns = this._getEvents()[eventName]; + if (BI.isArray(fns)) { + if (BI.isArguments(arguments[1])) { + for (let i = 0; i < fns.length; i++) { + if (fns[i].apply(this, arguments[1]) === false) { + return false; } - } else { - var args = Array.prototype.slice.call(arguments, 1); - for (var i = 0; i < fns.length; i++) { - if (fns[i].apply(this, args) === false) { - return false; - } + } + } else { + const args = Array.prototype.slice.call(arguments, 1); + for (let i = 0; i < fns.length; i++) { + if (fns[i].apply(this, args) === false) { + return false; } } } - return true; - }, - - destroy: function () { - this.destroyed && this.destroyed(); - this._purgeRef(); - this.purgeListeners(); } - }); - BI.OB = BI.OB || OB; -})(); + + return true; + } + + destroy() { + this.destroyed && this.destroyed(); + this._purgeRef(); + this.purgeListeners(); + } +} + +// BI.OB = BI.OB || OB; + +BI.extend(BI, { OB }); diff --git a/src/core/4.widget.js b/src/core/4.widget.js index e541191df..1e6c4b746 100644 --- a/src/core/4.widget.js +++ b/src/core/4.widget.js @@ -6,1078 +6,1075 @@ * @cfg {JSON} options 配置属性 */ -!(function () { - var cancelAnimationFrame = - _global.cancelAnimationFrame || - _global.webkitCancelAnimationFrame || - _global.mozCancelAnimationFrame || - _global.oCancelAnimationFrame || - _global.msCancelAnimationFrame || - _global.clearTimeout; - - var requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; - - function callLifeHook(self, life) { - var hooks = [], hook; - hook = self[life]; - if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); - } - hook = self.options[life]; - if (hook) { - hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); - } - BI.each(hooks, function (i, hook) { - hook.call(self); +import BI from "./2.base"; +import OB from "./3.ob"; + +const cancelAnimationFrame = + _global.cancelAnimationFrame || + _global.webkitCancelAnimationFrame || + _global.mozCancelAnimationFrame || + _global.oCancelAnimationFrame || + _global.msCancelAnimationFrame || + _global.clearTimeout; + +const requestAnimationFrame = _global.requestAnimationFrame || _global.webkitRequestAnimationFrame || _global.mozRequestAnimationFrame || _global.oRequestAnimationFrame || _global.msRequestAnimationFrame || _global.setTimeout; + +function callLifeHook(self, life) { + let hooks = [], hook; + hook = self[life]; + if (hook) { + hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + } + hook = self.options[life]; + if (hook) { + hooks = hooks.concat(BI.isArray(hook) ? hook : [hook]); + } + BI.each(hooks, function (i, hook) { + hook.call(self); + }); +} + +export default class Widget extends OB { + _defaultConfig () { + return BI.extend(super._defaultConfig(), { + root: false, + tagName: "div", + attributes: null, + data: null, + key: null, + + tag: null, + disabled: false, + invisible: false, + animation: "", + animationDuring: 0, + invalid: false, + baseCls: "", + extraCls: "", + cls: "", + css: null + + // vdom: false }); } - BI.Widget = BI.Widget || BI.inherit(BI.OB, { - _defaultConfig: function () { - return BI.extend(BI.Widget.superclass._defaultConfig.apply(this), { - root: false, - tagName: "div", - attributes: null, - data: null, - key: null, - - tag: null, - disabled: false, - invisible: false, - animation: "", - animationDuring: 0, - invalid: false, - baseCls: "", - extraCls: "", - cls: "", - css: null - - // vdom: false - }); - }, + _constructor () { - _constructor: function () { - - }, + } - // 覆盖父类的_constructor方法,widget不走ob的生命周期 - _constructed: function () { - if (this.setup) { - pushTarget(this); - var delegate = this.setup(this.options); - if (BI.isPlainObject(delegate)) { - // 如果setup返回一个json,即对外暴露的方法 - BI.extend(this, delegate); - } else { - this.render = delegate; - } - popTarget(); + // 覆盖父类的_constructor方法,widget不走ob的生命周期 + _constructed () { + if (this.setup) { + pushTarget(this); + const delegate = this.setup(this.options); + if (BI.isPlainObject(delegate)) { + // 如果setup返回一个json,即对外暴露的方法 + BI.extend(this, delegate); + } else { + this.render = delegate; } - }, + popTarget(); + } + } - _lazyConstructor: function () { - if (!this.__constructed) { - this.__constructed = true; - this._init(); - this._initRef(); - } - }, + _lazyConstructor () { + if (!this.__constructed) { + this.__constructed = true; + this._init(); + this._initRef(); + } + } - // 生命周期函数 - beforeInit: null, + // // 生命周期函数 + // beforeInit = null; - beforeRender: null, + // beforeRender = null; - beforeCreate: null, + // beforeCreate = null - created: null, + // created = null - render: null, + // render = null - beforeMount: null, + // beforeMount = null - mounted: null, - // 不想重写mounted时用 - _mounted: null, + // mounted = null + // // 不想重写mounted时用 + // _mounted = null - shouldUpdate: null, + // shouldUpdate = null - update: null, + // update = null - beforeUpdate: null, + // beforeUpdate = null - updated: null, + // updated = null - beforeDestroy: null, + // beforeDestroy = null - destroyed: null, - // 不想重写destroyed时用 - _destroyed: null, + // destroyed = null + // // 不想重写destroyed时用 + // _destroyed = null + + _init() { + super._init(...arguments); + this._initVisual(); + this._initState(); + this._initRender(); + } - _init: function () { - BI.Widget.superclass._init.apply(this, arguments); - this._initVisual(); - this._initState(); - this._initRender(); - }, + _initRender() { + let initCallbackCalled = false; + let renderCallbackCalled = false; - _initRender: function () { - var self = this; - var initCallbackCalled = false; - var renderCallbackCalled = false; + const init = () => { + // 加个保险 + if (initCallbackCalled === true) { + _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + return; + } + initCallbackCalled = true; - function init() { + const render = () => { // 加个保险 - if (initCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeInit内部的写法,callback只能执行一次"); + if (renderCallbackCalled === true) { + _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); return; } - initCallbackCalled = true; - - function render() { - // 加个保险 - if (renderCallbackCalled === true) { - _global.console && console.error("组件: 请检查beforeRender内部的写法,callback只能执行一次"); - return; - } - renderCallbackCalled = true; - self._render(); - self.__afterRender(); - } - - if (self.options.beforeRender || self.beforeRender) { - self.__async = true; - var beforeRenderResult = (self.options.beforeRender || self.beforeRender).call(self, render); - if (beforeRenderResult instanceof Promise) { - beforeRenderResult.then(render).catch(function (e) { - _global.console && console.error(e); - render(); - }); - } - } else { - self._render(); - self.__afterRender(); - } + renderCallbackCalled = true; + this._render(); + this.__afterRender(); } - if (this.options.beforeInit || this.beforeInit) { - this.__asking = true; - var beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); - if (beforeInitResult instanceof Promise) { - beforeInitResult.then(init).catch(function (e) { + if (this.options.beforeRender || this.beforeRender) { + this.__async = true; + const beforeRenderResult = (this.options.beforeRender || this.beforeRender).call(this, render); + if (beforeRenderResult instanceof Promise) { + beforeRenderResult.then(render).catch(function (e) { _global.console && console.error(e); - init(); + render(); }); } } else { - init(); + this._render(); + this.__afterRender(); } - }, + } - __afterRender: function () { - pushTarget(this); - var async = this.__async; - this.__async = false; - if (async && this._isMounted) { - callLifeHook(this, "beforeMount"); - this._mount(); - callLifeHook(this, "mounted"); - this.fireEvent(BI.Events.MOUNT); - } else { - this._mount(); + if (this.options.beforeInit || this.beforeInit) { + this.__asking = true; + const beforeInitResult = (this.options.beforeInit || this.beforeInit).call(this, init); + if (beforeInitResult instanceof Promise) { + beforeInitResult.then(init).catch(function (e) { + _global.console && console.error(e); + init(); + }); } - popTarget(); - }, + } else { + init(); + } + } - _render: function () { - this.__asking = false; - pushTarget(this); - callLifeHook(this, "beforeCreate"); - this._initElement(); - this._initEffects(); - callLifeHook(this, "created"); - popTarget(); - }, - - _initCurrent: function () { - var self = this, o = this.options; - this._initElementWidth(); - this._initElementHeight(); - if (o._baseCls || o.baseCls || o.extraCls) { - this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); - } - if (o.cls) { - if (BI.isFunction(o.cls)) { - var cls = this.__watch(o.cls, function (context, newValue) { - self.element.removeClass(cls).addClass(cls = newValue); - }); - this.element.addClass(cls); - } else { - this.element.addClass(o.cls); - } - } - // if (o.key != null) { - // this.element.attr("key", o.key); - // } - if (o.attributes) { - this.element.attr(o.attributes); - } - if (o.data) { - this.element.data(o.data); - } - if (o.css) { - if (BI.isFunction(o.css)) { - var css = this.__watch(o.css, function (context, newValue) { - for (var k in css) { - if (BI.isNull(newValue[k])) { - newValue[k] = ""; - } - } - self.element.css(css = newValue); - }); - this.element.css(css); - } else { - this.element.css(o.css); - } - } - }, - - __watch: function (getter, handler, options) { - var self = this; - if (_global.Fix) { - this._watchers = this._watchers || []; - var watcher = new Fix.Watcher(null, function () { - return getter.call(self, self); - }, (handler && function (v) { - handler.call(self, self, v); - }) || BI.emptyFn, BI.extend({ deep: true }, options)); - this._watchers.push(function unwatchFn() { - watcher.teardown(); + __afterRender() { + pushTarget(this); + const async = this.__async; + this.__async = false; + if (async && this._isMounted) { + callLifeHook(this, "beforeMount"); + this._mount(); + callLifeHook(this, "mounted"); + this.fireEvent(BI.Events.MOUNT); + } else { + this._mount(); + } + popTarget(); + } + + _render() { + this.__asking = false; + pushTarget(this); + callLifeHook(this, "beforeCreate"); + this._initElement(); + this._initEffects(); + callLifeHook(this, "created"); + popTarget(); + } + + _initCurrent() { + const o = this.options; + this._initElementWidth(); + this._initElementHeight(); + if (o._baseCls || o.baseCls || o.extraCls) { + this.element.addClass((o._baseCls || "") + " " + (o.baseCls || "") + " " + (o.extraCls || "")); + } + if (o.cls) { + if (BI.isFunction(o.cls)) { + const cls = this.__watch(o.cls, (context, newValue) => { + this.element.removeClass(cls).addClass(cls = newValue); }); - return watcher.value; + this.element.addClass(cls); } else { - return getter(); + this.element.addClass(o.cls); } - }, - - /** - * 初始化根节点 - * @private - */ - _initRoot: function () { - var o = this.options; - this.widgetName = o.widgetName || BI.uniqueId("widget"); - this._isRoot = o.root; - this._children = {}; - if (BI.isWidget(o.element)) { - this.element = this.options.element.element; - this._parent = o.element; - this._parent.addWidget(this.widgetName, this); - } else if (o.element) { - this.element = BI.Widget._renderEngine.createElement(this); - this._isRoot = true; + } + // if (o.key != null) { + // this.element.attr("key", o.key); + // } + if (o.attributes) { + this.element.attr(o.attributes); + } + if (o.data) { + this.element.data(o.data); + } + if (o.css) { + if (BI.isFunction(o.css)) { + const css = this.__watch(o.css, (context, newValue) => { + for (const k in css) { + if (BI.isNull(newValue[k])) { + newValue[k] = ""; + } + } + this.element.css(css = newValue); + }); + this.element.css(css); } else { - this.element = BI.Widget._renderEngine.createElement(this); - } - this.element._isWidget = true; - // var widgets = this.element.data("__widgets") || []; - // widgets.push(this); - // this.element.data("__widgets", widgets); - this._initCurrent(); - }, - - _initElementWidth: function () { - var o = this.options; - if (BI.isWidthOrHeight(o.width)) { - this.element.css("width", BI.pixFormat(o.width)); + this.element.css(o.css); } - }, + } + } + + __watch(getter, handler, options) { + if (_global.Fix) { + this._watchers = this._watchers || []; + const watcher = new Fix.Watcher(null, () => { + return getter.call(this, this); + }, (handler && ((v) => { + handler.call(this, this, v); + })) || BI.emptyFn, BI.extend({ deep: true }, options)); + this._watchers.push(() => { + watcher.teardown(); + }); + return watcher.value; + } else { + return getter(); + } + } + + /** + * 初始化根节点 + * @private + */ + _initRoot() { + const o = this.options; + this.widgetName = o.widgetName || BI.uniqueId("widget"); + this._isRoot = o.root; + this._children = {}; + if (BI.isWidget(o.element)) { + this.element = this.options.element.element; + this._parent = o.element; + this._parent._children && this._parent.addWidget(this.widgetName, this); + } else if (o.element) { + this.element = BI.Widget._renderEngine.createElement(this); + this._isRoot = true; + } else { + this.element = BI.Widget._renderEngine.createElement(this); + } + this.element._isWidget = true; + // const widgets = this.element.data("__widgets") || []; + // widgets.push(this); + // this.element.data("__widgets", widgets); + this._initCurrent(); + } + + _initElementWidth() { + const o = this.options; + if (BI.isWidthOrHeight(o.width)) { + this.element.css("width", BI.pixFormat(o.width)); + } + } - _initElementHeight: function () { - var o = this.options; - if (BI.isWidthOrHeight(o.height)) { - this.element.css("height", BI.pixFormat(o.height)); + _initElementHeight() { + const o = this.options; + if (BI.isWidthOrHeight(o.height)) { + this.element.css("height", BI.pixFormat(o.height)); + } + } + + _initVisual() { + const o = this.options; + if (o.invisible) { + const invisible = o.invisible = BI.isFunction(o.invisible) ? this.__watch(o.invisible, (context, newValue) => { + this.setVisible(!newValue); + }) : o.invisible; + if (invisible) { + // 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性 + this.__setElementVisible(false); } - }, - - _initVisual: function () { - var self = this, o = this.options; - if (o.invisible) { - var invisible = o.invisible = BI.isFunction(o.invisible) ? this.__watch(o.invisible, function (context, newValue) { - self.setVisible(!newValue); - }) : o.invisible; - if (invisible) { - // 用display属性做显示和隐藏,否则jquery会在显示时将display设为block会覆盖掉display:flex属性 - this.__setElementVisible(false); + } + } + + _initEffects() { + const o = this.options; + if (o.disabled || o.invalid) { + if (this.options.disabled) { + const disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, (context, newValue) => { + this.setEnable(!newValue); + }) : o.disabled; + if (disabled) { + this.setEnable(false); } } - }, - - _initEffects: function () { - var self = this, o = this.options; - if (o.disabled || o.invalid) { - if (this.options.disabled) { - var disabled = o.disabled = BI.isFunction(o.disabled) ? this.__watch(o.disabled, function (context, newValue) { - self.setEnable(!newValue); - }) : o.disabled; - if (disabled) { - this.setEnable(false); - } - } - if (this.options.invalid) { - var invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, function (context, newValue) { - self.setValid(!newValue); - }) : o.invalid; - if (invalid) { - this.setValid(false); - } + if (this.options.invalid) { + const invalid = o.invalid = BI.isFunction(o.invalid) ? this.__watch(o.invalid, (context, newValue) => { + this.setValid(!newValue); + }) : o.invalid; + if (invalid) { + this.setValid(false); } } - if (o.effect) { - if (BI.isArray(o.effect)) { - if (BI.isArray(o.effect[0])) { - BI.each(o.effect, function (i, effect) { - self.__watch(effect[0], effect[1]); - }); - } else { - self.__watch(o.effect[0], o.effect[1]); - } + } + if (o.effect) { + if (BI.isArray(o.effect)) { + if (BI.isArray(o.effect[0])) { + BI.each(o.effect, (i, effect) => { + this.__watch(effect[0], effect[1]); + }); } else { - this.__watch(o.effect); - } - } - }, - - _initState: function () { - this._isMounted = false; - this._isDestroyed = false; - }, - - __initWatch: function () { - // initWatch拦截的方法 - }, - - _initElement: function () { - var self = this; - this.__isMounting = true; - // 当开启worker模式时,可以通过$render来实现另一种效果 - var workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); - var render = BI.isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); - var els = render && render.call(this); - els = this.options.configRender ? this.options.configRender.call(this, els) : els; - els = BI.Plugin.getRender(this.options.type, els); - if (BI.isPlainObject(els)) { - els = [els]; - } - this.__initWatch(); - if (BI.isArray(els)) { - BI.each(els, function (i, el) { - if (el) { - BI._lazyCreateWidget(el, { - element: self - }); - } - }); - } - }, - - _setParent: function (parent) { - this._parent = parent; - }, - - /** - * - * @param force 是否强制挂载子节点 - * @param deep 子节点是否也是按照当前force处理 - * @param lifeHook 生命周期钩子触不触发,默认触发 - * @param predicate 递归每个widget的回调 - * @param layer 组件层级 - * @returns {boolean} - * @private - */ - _mount: function (force, deep, lifeHook, predicate, layer) { - var self = this; - if (!force && (this._isMounted || !this.isVisible() || this.__asking === true || !(this._isRoot === true || (this._parent && this._parent._isMounted === true)))) { - return false; - } - layer = layer || 0; - lifeHook !== false && !this.__async && callLifeHook(this, "beforeMount"); - this._isMounted = true; - this.__isMounting = false; - for (var key in this._children) { - var child = this._children[key]; - child._mount && child._mount(deep ? force : false, deep, lifeHook, predicate, layer + 1); - } - if (this._parent) { - if (!this._parent.isEnabled()) { - this._setEnable(false); - } - if (!this._parent.isValid()) { - this._setValid(false); - } - } - this._mountChildren && this._mountChildren(); - if (layer === 0) { - // mounted里面会执行scrollTo之类的方法,如果放宏任务里会闪 - // setTimeout(function () { - self.__afterMount(lifeHook, predicate); - // }, 0); - } - return true; - }, - - __afterMount: function (lifeHook, predicate) { - if (this._isMounted) { - for (var key in this._children) { - var child = this._children[key]; - child.__afterMount && child.__afterMount(lifeHook, predicate); - } - if (lifeHook !== false && !this.__async) { - callLifeHook(this, "_mounted"); - callLifeHook(this, "mounted"); - this.fireEvent(BI.Events.MOUNT); + this.__watch(o.effect[0], o.effect[1]); } - predicate && predicate(this); + } else { + this.__watch(o.effect); } - }, + } + } - _mountChildren: null, + _initState() { + this._isMounted = false; + this._isDestroyed = false; + } - _update: function (nextProps, shouldUpdate) { - callLifeHook(this, "beforeUpdate"); - if (shouldUpdate) { - var res = this.update && this.update(nextProps, shouldUpdate); - } - callLifeHook(this, "updated"); - return res; - }, - - isMounted: function () { - return this._isMounted; - }, - - isDestroyed: function () { - return this._isDestroyed; - }, - - setWidth: function (w) { - this.options.width = w; - this._initElementWidth(); - }, - - setHeight: function (h) { - this.options.height = h; - this._initElementHeight(); - }, - - _setEnable: function (enable) { - if (enable === true) { - this.options._disabled = false; - } else if (enable === false) { - this.options._disabled = true; - } - // 递归将所有子组件使能 - BI.each(this._children, function (i, child) { - !child._manualSetEnable && child._setEnable && child._setEnable(enable); + __initWatch() { + // initWatch拦截的方法 + } + + _initElement() { + this.__isMounting = true; + // 当开启worker模式时,可以通过$render来实现另一种效果 + const workerMode = BI.Providers.getProvider("bi.provider.system").getWorkerMode(); + const render = BI.isFunction(this.options.render) ? this.options.render : (workerMode ? (this.$render || this.render) : this.render); + let els = render && render.call(this); + els = this.options.configRender ? this.options.configRender.call(this, els) : els; + els = BI.Plugin.getRender(this.options.type, els); + if (BI.isPlainObject(els)) { + els = [els]; + } + this.__initWatch(); + if (BI.isArray(els)) { + BI.each(els, (i, el) => { + if (el) { + BI._lazyCreateWidget(el, { + element: this + }); + } }); - }, + } + } + + _setParent(parent) { + this._parent = parent; + } - _setValid: function (valid) { - if (valid === true) { - this.options._invalid = false; - } else if (valid === false) { - this.options._invalid = true; + /** + * + * @param force 是否强制挂载子节点 + * @param deep 子节点是否也是按照当前force处理 + * @param lifeHook 生命周期钩子触不触发,默认触发 + * @param predicate 递归每个widget的回调 + * @param layer 组件层级 + * @returns {boolean} + * @private + */ + _mount(force, deep, lifeHook, predicate, layer) { + if (!force && (this._isMounted || !this.isVisible() || this.__asking === true || !(this._isRoot === true || (this._parent && this._parent._isMounted === true)))) { + return false; + } + layer = layer || 0; + lifeHook !== false && !this.__async && callLifeHook(this, "beforeMount"); + this._isMounted = true; + this.__isMounting = false; + for (const key in this._children) { + const child = this._children[key]; + child._mount && child._mount(deep ? force : false, deep, lifeHook, predicate, layer + 1); + } + if (this._parent) { + if (!this._parent.isEnabled()) { + this._setEnable(false); } - // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { - !child._manualSetValid && child._setValid && child._setValid(valid); - }); - }, + if (!this._parent.isValid()) { + this._setValid(false); + } + } + this._mountChildren && this._mountChildren(); + if (layer === 0) { + // mounted里面会执行scrollTo之类的方法,如果放宏任务里会闪 + // setTimeout(function () { + this.__afterMount(lifeHook, predicate); + // }, 0); + } + return true; + } - _setVisible: function (visible) { - if (visible === true) { - this.options.invisible = false; - } else if (visible === false) { - this.options.invisible = true; + __afterMount(lifeHook, predicate) { + if (this._isMounted) { + for (const key in this._children) { + const child = this._children[key]; + child.__afterMount && child.__afterMount(lifeHook, predicate); } - }, - - setEnable: function (enable) { - this._manualSetEnable = true; - this.options.disabled = !enable; - this._setEnable(enable); - if (enable === true) { - this.element.removeClass("base-disabled disabled"); - } else if (enable === false) { - this.element.addClass("base-disabled disabled"); + if (lifeHook !== false && !this.__async) { + callLifeHook(this, "_mounted"); + callLifeHook(this, "mounted"); + this.fireEvent(BI.Events.MOUNT); } - }, - - __setElementVisible: function (visible) { - this.element.css("display", visible ? "" : "none"); - }, - - _innerSetVisible: function (visible) { - var self = this, o = this.options; - var lastVisible = !o.invisible; - this._setVisible(visible); - if (visible === true) { - // 用this.element.show()会把display属性改成block - this.__setElementVisible(true); - this._mount(); - if (o.animation && !lastVisible) { - this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); - if (this._requestAnimationFrame) { - cancelAnimationFrame(this._requestAnimationFrame); - } - this._requestAnimationFrame = function () { - self.element.addClass(o.animation + "-enter-active"); - }; - requestAnimationFrame(this._requestAnimationFrame); - if (this._animationDuring) { - clearTimeout(this._animationDuring); - } - this._animationDuring = setTimeout(function () { - self.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); - }, o.animationDuring); + predicate && predicate(this); + } + } + + // _mountChildren = null; + + _update(nextProps, shouldUpdate) { + callLifeHook(this, "beforeUpdate"); + if (shouldUpdate) { + const res = this.update && this.update(nextProps, shouldUpdate); + } + callLifeHook(this, "updated"); + return res; + } + + isMounted() { + return this._isMounted; + } + + isDestroyed() { + return this._isDestroyed; + } + + setWidth(w) { + this.options.width = w; + this._initElementWidth(); + } + + setHeight(h) { + this.options.height = h; + this._initElementHeight(); + } + + _setEnable(enable) { + if (enable === true) { + this.options._disabled = false; + } else if (enable === false) { + this.options._disabled = true; + } + // 递归将所有子组件使能 + BI.each(this._children, function (i, child) { + !child._manualSetEnable && child._setEnable && child._setEnable(enable); + }); + } + + _setValid(valid) { + if (valid === true) { + this.options._invalid = false; + } else if (valid === false) { + this.options._invalid = true; + } + // 递归将所有子组件使有效 + BI.each(this._children, function (i, child) { + !child._manualSetValid && child._setValid && child._setValid(valid); + }); + } + + _setVisible(visible) { + if (visible === true) { + this.options.invisible = false; + } else if (visible === false) { + this.options.invisible = true; + } + } + + setEnable(enable) { + this._manualSetEnable = true; + this.options.disabled = !enable; + this._setEnable(enable); + if (enable === true) { + this.element.removeClass("base-disabled disabled"); + } else if (enable === false) { + this.element.addClass("base-disabled disabled"); + } + } + + __setElementVisible(visible) { + this.element.css("display", visible ? "" : "none"); + } + + _innerSetVisible(visible) { + const o = this.options; + const lastVisible = !o.invisible; + this._setVisible(visible); + if (visible === true) { + // 用this.element.show()会把display属性改成block + this.__setElementVisible(true); + this._mount(); + if (o.animation && !lastVisible) { + this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active").addClass(o.animation + "-enter"); + if (this._requestAnimationFrame) { + cancelAnimationFrame(this._requestAnimationFrame); } - } else if (visible === false) { - if (o.animation && lastVisible) { - this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); - if (this._requestAnimationFrame) { - cancelAnimationFrame(this._requestAnimationFrame); - } - this._requestAnimationFrame = function () { - self.element.addClass(o.animation + "-leave-active"); - }; - requestAnimationFrame(this._requestAnimationFrame); - if (this._animationDuring) { - clearTimeout(this._animationDuring); - } - this._animationDuring = setTimeout(function () { - self.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); - self.__setElementVisible(false); - }, o.animationDuring); - } else { - this.__setElementVisible(false); + this._requestAnimationFrame = () => { + this.element.addClass(o.animation + "-enter-active"); + }; + requestAnimationFrame(this._requestAnimationFrame); + if (this._animationDuring) { + clearTimeout(this._animationDuring); } + this._animationDuring = setTimeout(() => { + this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active"); + }, o.animationDuring); } - }, - - setVisible: function (visible) { - this._innerSetVisible(visible); - this.fireEvent(BI.Events.VIEW, visible); - }, - - setValid: function (valid) { - this._manualSetValid = true; - this.options.invalid = !valid; - this._setValid(valid); - if (valid === true) { - this.element.removeClass("base-invalid invalid"); - } else if (valid === false) { - this.element.addClass("base-invalid invalid"); + } else if (visible === false) { + if (o.animation && lastVisible) { + this.element.removeClass(o.animation + "-enter").removeClass(o.animation + "-enter-active").addClass(o.animation + "-leave"); + if (this._requestAnimationFrame) { + cancelAnimationFrame(this._requestAnimationFrame); + } + this._requestAnimationFrame = () => { + this.element.addClass(o.animation + "-leave-active"); + }; + requestAnimationFrame(this._requestAnimationFrame); + if (this._animationDuring) { + clearTimeout(this._animationDuring); + } + this._animationDuring = setTimeout(() => { + this.element.removeClass(o.animation + "-leave").removeClass(o.animation + "-leave-active"); + this.__setElementVisible(false); + }, o.animationDuring); + } else { + this.__setElementVisible(false); } - }, + } + } - doBehavior: function () { - var args = arguments; - // 递归将所有子组件使有效 - BI.each(this._children, function (i, child) { - child.doBehavior && child.doBehavior.apply(child, args); - }); - }, + setVisible(visible) { + this._innerSetVisible(visible); + this.fireEvent(BI.Events.VIEW, visible); + } - getWidth: function () { - return this.options.width; - }, + setValid(valid) { + this._manualSetValid = true; + this.options.invalid = !valid; + this._setValid(valid); + if (valid === true) { + this.element.removeClass("base-invalid invalid"); + } else if (valid === false) { + this.element.addClass("base-invalid invalid"); + } + } - getHeight: function () { - return this.options.height; - }, + doBehavior() { + const args = arguments; + // 递归将所有子组件使有效 + BI.each(this._children, function (i, child) { + child.doBehavior && child.doBehavior.apply(child, args); + }); + } - addWidget: function (name, widget) { - var self = this; - if (name instanceof BI.Widget) { - widget = name; - name = widget.getName(); - } - if (BI.isKey(name)) { - name = name + ""; - } - name = name || widget.getName() || BI.uniqueId("widget"); - if (this._children[name]) { - throw new Error("组件:组件名已存在,不能进行添加"); - } - widget._setParent && widget._setParent(this); - widget.on(BI.Events.DESTROY, function () { - BI.remove(self._children, this); - }); - return (this._children[name] = widget); - }, + getWidth() { + return this.options.width; + } - getWidgetByName: function (name) { - if (!BI.isKey(name) || name === this.getName()) { - return this; - } + getHeight() { + return this.options.height; + } + + addWidget(name, widget) { + const self = this; + if (name instanceof BI.Widget) { + widget = name; + name = widget.getName(); + } + if (BI.isKey(name)) { name = name + ""; - var widget = void 0, other = {}; - BI.any(this._children, function (i, wi) { - if (i === name) { - widget = wi; - return true; - } - other[i] = wi; - }); - if (!widget) { - BI.any(other, function (i, wi) { - return (widget = wi.getWidgetByName(i)); - }); - } - return widget; - }, + } + name = name || widget.getName() || BI.uniqueId("widget"); + if (this._children[name]) { + throw new Error("组件:组件名已存在,不能进行添加"); + } + widget._setParent && widget._setParent(this); + widget.on(BI.Events.DESTROY, function () { + // TODO: self待删 + BI.remove(self._children, this); + }); + return (this._children[name] = widget); + } - removeWidget: function (nameOrWidget) { - if (BI.isWidget(nameOrWidget)) { - BI.remove(this._children, nameOrWidget); - } else { - delete this._children[nameOrWidget]; + getWidgetByName(name) { + if (!BI.isKey(name) || name === this.getName()) { + return this; + } + name = name + ""; + let widget = void 0, other = {}; + BI.any(this._children, function (i, wi) { + if (i === name) { + widget = wi; + return true; } - }, + other[i] = wi; + }); + if (!widget) { + BI.any(other, function (i, wi) { + return (widget = wi.getWidgetByName(i)); + }); + } + return widget; + } - hasWidget: function (name) { - return this._children[name] != null; - }, + removeWidget(nameOrWidget) { + if (BI.isWidget(nameOrWidget)) { + BI.remove(this._children, nameOrWidget); + } else { + delete this._children[nameOrWidget]; + } + } - getName: function () { - return this.widgetName; - }, + hasWidget(name) { + return this._children[name] != null; + } - setTag: function (tag) { - this.options.tag = tag; - }, + getName() { + return this.widgetName; + } - getTag: function () { - return this.options.tag; - }, + setTag(tag) { + this.options.tag = tag; + } - attr: function (key, value) { - var self = this; - if (BI.isPlainObject(key)) { - BI.each(key, function (k, v) { - self.attr(k, v); - }); - return; - } - if (BI.isNotNull(value)) { - return this.options[key] = value; - } - return this.options[key]; - }, + getTag() { + return this.options.tag; + } - css: function (name, value) { - return this.element.css(name, value); - }, + attr(key, value) { + if (BI.isPlainObject(key)) { + BI.each(key, (k, v) => this.attr(k, v)); + return; + } + if (BI.isNotNull(value)) { + return this.options[key] = value; + } + return this.options[key]; + } - getText: function () { + css(name, value) { + return this.element.css(name, value); + } - }, + getText() { - setText: function (text) { + } - }, + setText(text) { - getValue: function () { + } - }, + getValue() { - setValue: function (value) { + } - }, + setValue(value) { - isEnabled: function () { - return this.options.disabled === true ? false : !this.options._disabled; - }, + } - isValid: function () { - return this.options.invalid === true ? false : !this.options._invalid; - }, + isEnabled() { + return this.options.disabled === true ? false : !this.options._disabled; + } - isVisible: function () { - return !this.options.invisible; - }, + isValid() { + return this.options.invalid === true ? false : !this.options._invalid; + } - disable: function () { - this.setEnable(false); - }, + isVisible() { + return !this.options.invisible; + } - enable: function () { - this.setEnable(true); - }, + disable() { + this.setEnable(false); + } - valid: function () { - this.setValid(true); - }, + enable() { + this.setEnable(true); + } - invalid: function () { - this.setValid(false); - }, + valid() { + this.setValid(true); + } - invisible: function () { - this.setVisible(false); - }, + invalid() { + this.setValid(false); + } - visible: function () { - this.setVisible(true); - }, + invisible() { + this.setVisible(false); + } - __d: function () { - BI.each(this._children, function (i, widget) { - widget && widget._unMount && widget._unMount(); - }); - this._children = {}; - }, - - // 主要是因为_destroy已经提供了protected方法 - __destroy: function () { - callLifeHook(this, "beforeDestroy"); - this.beforeDestroy = null; - this.__d(); - this._parent = null; - this._isMounted = false; - callLifeHook(this, "_destroyed"); - callLifeHook(this, "destroyed"); - this.destroyed = null; - this._isDestroyed = true; - // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - - }, - - _unMount: function () { - this._assetMounted(); - this.__destroy(); - this.fireEvent(BI.Events.UNMOUNT); - this.purgeListeners(); - }, - - _assetMounted: function () { - if (!this.isVisible()) { - this._setVisible(true); - this._mount(false, false, false); - this._setVisible(false); - } - }, + visible() { + this.setVisible(true); + } - _empty: function () { - this._assetMounted(); - BI.each(this._children, function (i, widget) { - widget && widget._unMount && widget._unMount(); - }); - this._children = {}; - this.element.empty(); - }, + __d() { + BI.each(this._children, function (i, widget) { + widget && widget._unMount && widget._unMount(); + }); + this._children = {}; + } - isolate: function () { - if (this._parent) { - this._parent.removeWidget(this); - } - BI.DOM.hang([this]); - }, + // 主要是因为_destroy已经提供了protected方法 + __destroy() { + callLifeHook(this, "beforeDestroy"); + this.beforeDestroy = null; + this.__d(); + this._parent = null; + this._isMounted = false; + callLifeHook(this, "_destroyed"); + callLifeHook(this, "destroyed"); + this.destroyed = null; + this._isDestroyed = true; + // this._purgeRef(); // 清除ref的时机还是要仔细考虑一下 - empty: function () { - this._empty(); - }, + } - // 默认的reset方法就是干掉重来 - reset: function () { - // 还在异步状态的不需要执行reset - if (this.__async === true || this.__asking === true) { - return; - } - // if (this.options.vdom) { - // var vnode = this._renderVNode(); - // BI.patchVNode(this.vnode, vnode); - // this.vnode = vnode; - // return; - // } - // this._isMounted = false; - // this.purgeListeners(); - - // 去掉组件绑定的watcher - BI.each(this._watchers, function (i, unwatches) { - unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; - BI.each(unwatches, function (j, unwatch) { - unwatch(); - }); - }); - this._watchers && (this._watchers = []); - this._assetMounted(); - this.__d(); - this.element.empty(); - this.element.unbind(); - this._initCurrent(); - this._init(); - // this._initRef(); - }, + _unMount() { + this._assetMounted(); + this.__destroy(); + this.fireEvent(BI.Events.UNMOUNT); + this.purgeListeners(); + } - _destroy: function () { - this._assetMounted(); - this.__destroy(); - this.element.destroy(); - this.purgeListeners(); - }, - - destroy: function () { - var self = this, o = this.options; - this._assetMounted(); - this.__destroy(); - if (o.animation) { - this._innerSetVisible(false); - setTimeout(function () { - self.element.destroy(); - }, o.animationDuring); - } else { - this.element.destroy(); - } - this.fireEvent(BI.Events.UNMOUNT); - this.fireEvent(BI.Events.DESTROY); - this._purgeRef(); - this.purgeListeners(); - } - }); - var context = null, current = null; - var contextStack = [], currentStack = []; - - BI.Widget.pushContext = function (_context) { - if (context) contextStack.push(context); - BI.Widget.context = context = _context; - }; - - BI.Widget.popContext = function () { - BI.Widget.context = context = contextStack.pop(); - }; - - BI.Widget.execWithContext = function (context, execFunc) { - BI.Widget.pushContext(context); - try { - execFunc(); - } catch (e) { - throw e; - } finally { - BI.Widget.popContext(); + _assetMounted() { + if (!this.isVisible()) { + this._setVisible(true); + this._mount(false, false, false); + this._setVisible(false); } - }; + } - function pushTarget(_current) { - if (current) currentStack.push(current); - BI.Widget.current = current = _current; + _empty () { + this._assetMounted(); + BI.each(this._children, function (i, widget) { + widget && widget._unMount && widget._unMount(); + }); + this._children = {}; + this.element.empty(); } - function popTarget() { - BI.Widget.current = current = currentStack.pop(); + isolate () { + if (this._parent) { + this._parent.removeWidget(this); + } + BI.DOM.hang([this]); } - BI.useStore = function (_store) { - if (current && current.store) { - return current.store; + empty () { + this._empty(); + } + + // 默认的reset方法就是干掉重来 + reset () { + // 还在异步状态的不需要执行reset + if (this.__async === true || this.__asking === true) { + return; } - if (current && current.$storeDelegate) { - return current.$storeDelegate; + // if (this.options.vdom) { + // const vnode = this._renderVNode(); + // BI.patchVNode(this.vnode, vnode); + // this.vnode = vnode; + // return; + // } + // this._isMounted = false; + // this.purgeListeners(); + + // 去掉组件绑定的watcher + BI.each(this._watchers, function (i, unwatches) { + unwatches = BI.isArray(unwatches) ? unwatches : [unwatches]; + BI.each(unwatches, function (j, unwatch) { + unwatch(); + }); + }); + this._watchers && (this._watchers = []); + this._assetMounted(); + this.__d(); + this.element.empty(); + this.element.unbind(); + this._initCurrent(); + this._init(); + // this._initRef(); + } + + _destroy() { + this._assetMounted(); + this.__destroy(); + this.element.destroy(); + this.purgeListeners(); + } + + destroy() { + const o = this.options; + this._assetMounted(); + this.__destroy(); + if (o.animation) { + this._innerSetVisible(false); + setTimeout(() => this.element.destroy(), o.animationDuring); + } else { + this.element.destroy(); } - if (current) { - var currentStore = current._store; - var delegate = {}, origin; - if (_global.Proxy) { - var proxy = new Proxy(delegate, { - get: function (target, key) { - return Reflect.get(origin, key); - }, - set: function (target, key, value) { - return Reflect.set(origin, key, value); - } - }); - current._store = function () { - origin = (_store || currentStore).apply(this, arguments); - delegate.$delegate = origin; - return origin; - }; - return current.$storeDelegate = proxy; - } + this.fireEvent(BI.Events.UNMOUNT); + this.fireEvent(BI.Events.DESTROY); + this._purgeRef(); + this.purgeListeners(); + } +}; + +BI.extend(BI, { Widget }); + + +let context = null, current = null; +const contextStack = [], currentStack = []; + +BI.Widget.pushContext = function (_context) { + if (context) contextStack.push(context); + BI.Widget.context = context = _context; +}; + +BI.Widget.popContext = function () { + BI.Widget.context = context = contextStack.pop(); +}; + +BI.Widget.execWithContext = function (context, execFunc) { + BI.Widget.pushContext(context); + try { + execFunc(); + } catch (e) { + throw e; + } finally { + BI.Widget.popContext(); + } +}; + +function pushTarget(_current) { + if (current) currentStack.push(current); + BI.Widget.current = current = _current; +} + +function popTarget() { + BI.Widget.current = current = currentStack.pop(); +} + +BI.useStore = function (_store) { + if (current && current.store) { + return current.store; + } + if (current && current.$storeDelegate) { + return current.$storeDelegate; + } + if (current) { + const currentStore = current._store; + let delegate = {}, origin; + if (_global.Proxy) { + const proxy = new Proxy(delegate, { + get: function (target, key) { + return Reflect.get(origin, key); + }, + set: function (target, key, value) { + return Reflect.set(origin, key, value); + } + }); current._store = function () { - var st = (_store || currentStore).apply(this, arguments); - BI.extend(delegate, st); - return st; + origin = (_store || currentStore).apply(this, arguments); + delegate.$delegate = origin; + return origin; }; - return current.$storeDelegate = delegate; + return current.$storeDelegate = proxy; } - }; - - BI.useContext = function (inject) { - // 通过组件找最近的store - var vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); - if (vm) { - if (inject) { - if (vm.$$computed && inject in vm.$$computed) { - return vm; - } - if (vm.$$state && inject in vm.$$state) { - return vm; - } - if (vm.$$model && inject in vm.$$model) { + current._store = function () { + const st = (_store || currentStore).apply(this, arguments); + BI.extend(delegate, st); + return st; + }; + return current.$storeDelegate = delegate; + } +}; + +BI.useContext = function (inject) { + // 通过组件找最近的store + const vm = BI.Widget.findStore(BI.Widget.current || BI.Widget.context); + if (vm) { + if (inject) { + if (vm.$$computed && inject in vm.$$computed) { + return vm; + } + if (vm.$$state && inject in vm.$$state) { + return vm; + } + if (vm.$$model && inject in vm.$$model) { + return vm; + } + while (vm) { + if (vm.$$context && inject in vm.$$context) { return vm; } - while (vm) { - if (vm.$$context && inject in vm.$$context) { - return vm; - } - vm = vm._parent; - } - return null; + vm = vm._parent; } + return null; } - return vm; - }; - - BI.watch = function (vm, watch, handler) { - // 必须要保证组件当前环境存在 - if (BI.Widget.current) { - if (vm instanceof BI.Model) { - var watchers = []; - if (BI.isKey(watch)) { - var k = watch; - watch = {}; - watch[k] = handler; - } - for (var key in watch) { - var innerHandler = watch[key]; - if (BI.isArray(handler)) { - for (var i = 0; i < handler.length; i++) { - watchers.push(Fix.watch(vm.model, key, innerHandler, { - store: vm - })); - } - } else { + } + return vm; +}; + +BI.watch = function (vm, watch, handler) { + // 必须要保证组件当前环境存在 + if (BI.Widget.current) { + if (vm instanceof BI.Model) { + const watchers = []; + if (BI.isKey(watch)) { + const k = watch; + watch = {}; + watch[k] = handler; + } + for (const key in watch) { + const innerHandler = watch[key]; + if (BI.isArray(handler)) { + for (let i = 0; i < handler.length; i++) { watchers.push(Fix.watch(vm.model, key, innerHandler, { store: vm })); } + } else { + watchers.push(Fix.watch(vm.model, key, innerHandler, { + store: vm + })); } - // vm中一定有_widget - BI.Widget.current._watchers || (BI.Widget.current._watchers = []); - BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); - return; } - handler = watch; - watch = vm; - BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); - BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + // vm中一定有_widget + BI.Widget.current._watchers || (BI.Widget.current._watchers = []); + BI.Widget.current._watchers = BI.Widget.current._watchers.concat(watchers); + return; } - }; + handler = watch; + watch = vm; + BI.Widget.current.$watchDelayCallbacks || (BI.Widget.current.$watchDelayCallbacks = []); + BI.Widget.current.$watchDelayCallbacks.push([watch, handler]); + } +}; - BI.onBeforeMount = function (beforeMount) { - if (current) { - if (current.__isMounting) { - beforeMount(); - return; - } - if (!current.beforeMount) { - current.beforeMount = []; - } else if (!BI.isArray(current.beforeMount)) { - current.beforeMount = [current.beforeMount]; - } - current.beforeMount.push(beforeMount); +BI.onBeforeMount = function (beforeMount) { + if (current) { + if (current.__isMounting) { + beforeMount(); + return; } - }; - BI.onMounted = function (mounted) { - if (current) { - if (current._isMounted && !this.__async) { - mounted(); - return; - } - if (!current.mounted) { - current.mounted = []; - } else if (!BI.isArray(current.mounted)) { - current.mounted = [current.mounted]; - } - current.mounted.push(mounted); + if (!current.beforeMount) { + current.beforeMount = []; + } else if (!BI.isArray(current.beforeMount)) { + current.beforeMount = [current.beforeMount]; } - }; - BI.onBeforeUnmount = function (beforeDestroy) { - if (current) { - if (!current.beforeDestroy) { - current.beforeDestroy = []; - } else if (!BI.isArray(current.beforeDestroy)) { - current.beforeDestroy = [current.beforeDestroy]; - } - current.beforeDestroy.push(beforeDestroy); + current.beforeMount.push(beforeMount); + } +}; +BI.onMounted = function (mounted) { + if (current) { + if (current._isMounted && !this.__async) { + mounted(); + return; } - }; - BI.onUnmounted = function (destroyed) { - if (current) { - if (!current.destroyed) { - current.destroyed = []; - } else if (!BI.isArray(current.destroyed)) { - current.destroyed = [current.destroyed]; - } - current.destroyed.push(destroyed); + if (!current.mounted) { + current.mounted = []; + } else if (!BI.isArray(current.mounted)) { + current.mounted = [current.mounted]; } - }; - - BI.Widget.registerRenderEngine = function (engine) { - BI.Widget._renderEngine = engine; - }; - BI.Widget.registerRenderEngine({ - createElement: function (widget) { - if (BI.isWidget(widget)) { - var o = widget.options; - if (o.element) { - return BI.$(o.element); - } - if (o.tagName) { - return BI.$(document.createElement(o.tagName)); - } - return BI.$(document.createDocumentFragment()); - } - return BI.$(widget); - }, - createFragment: function () { - return document.createDocumentFragment(); + current.mounted.push(mounted); + } +}; +BI.onBeforeUnmount = function (beforeDestroy) { + if (current) { + if (!current.beforeDestroy) { + current.beforeDestroy = []; + } else if (!BI.isArray(current.beforeDestroy)) { + current.beforeDestroy = [current.beforeDestroy]; } - }); - - BI.mount = function (widget, container, predicate, hydrate) { - if (hydrate === true) { - // 将widget的element元素都挂载好,并建立相互关系 - widget.element.data("__widgets", [widget]); - var res = widget._mount(true, false, false, function (w) { - BI.each(w._children, function (i, child) { - var ws = child.element.data("__widgets"); - if (!ws) { - ws = []; - } - ws.push(child); - child.element.data("__widgets", ws); - }); - predicate && predicate.apply(this, arguments); - }); - // 将新的dom树属性(事件等)patch到已存在的dom上 - var c = BI.Widget._renderEngine.createElement; - BI.DOM.patchProps(widget.element, c(c(container).children()[0])); - - var triggerLifeHook = function (w) { - w.beforeMount && w.beforeMount(); - w.mounted && w.mounted(); - BI.each(w._children, function (i, child) { - triggerLifeHook(child); - }); - }; - // 最后触发组件树生命周期函数 - triggerLifeHook(widget); - return res; + current.beforeDestroy.push(beforeDestroy); + } +}; +BI.onUnmounted = function (destroyed) { + if (current) { + if (!current.destroyed) { + current.destroyed = []; + } else if (!BI.isArray(current.destroyed)) { + current.destroyed = [current.destroyed]; } - if (container) { - BI.Widget._renderEngine.createElement(container).append(widget.element); + current.destroyed.push(destroyed); + } +}; + +BI.Widget.registerRenderEngine = function (engine) { + BI.Widget._renderEngine = engine; +}; +BI.Widget.registerRenderEngine({ + createElement: function (widget) { + if (BI.isWidget(widget)) { + const o = widget.options; + if (o.element) { + return BI.$(o.element); + } + if (o.tagName) { + return BI.$(document.createElement(o.tagName)); + } + return BI.$(document.createDocumentFragment()); } - return widget._mount(true, false, false, predicate); - }; -})(); + return BI.$(widget); + }, + createFragment: function () { + return document.createDocumentFragment(); + } +}); + +BI.mount = function (widget, container, predicate, hydrate) { + if (hydrate === true) { + // 将widget的element元素都挂载好,并建立相互关系 + widget.element.data("__widgets", [widget]); + const res = widget._mount(true, false, false, function (w) { + BI.each(w._children, function (i, child) { + const ws = child.element.data("__widgets"); + if (!ws) { + ws = []; + } + ws.push(child); + child.element.data("__widgets", ws); + }); + predicate && predicate.apply(this, arguments); + }); + // 将新的dom树属性(事件等)patch到已存在的dom上 + const c = BI.Widget._renderEngine.createElement; + BI.DOM.patchProps(widget.element, c(c(container).children()[0])); + + const triggerLifeHook = function (w) { + w.beforeMount && w.beforeMount(); + w.mounted && w.mounted(); + BI.each(w._children, function (i, child) { + triggerLifeHook(child); + }); + }; + // 最后触发组件树生命周期函数 + triggerLifeHook(widget); + return res; + } + if (container) { + BI.Widget._renderEngine.createElement(container).append(widget.element); + } + return widget._mount(true, false, false, predicate); +}; diff --git a/src/core/action/action.js b/src/core/action/action.js index 3639c00e5..3ed7acd44 100644 --- a/src/core/action/action.js +++ b/src/core/action/action.js @@ -5,22 +5,23 @@ * @extends BI.OB * @abstract */ -BI.Action = BI.inherit(BI.OB, { - props: function () { - return { - src: null, - tar: null - }; - }, +import OB from "../3.ob"; +export default class Action extends OB { + props = { + src: null, + tar: null + }; - actionPerformed: function (src, tar, callback) { + actionPerformed(src, tar, callback) { - }, + } - actionBack: function (tar, src, callback) { + actionBack(tar, src, callback) { } -}); +} + +BI.extend(BI, { Action }); BI.ActionFactory = { createAction: function (key, options) { diff --git a/src/core/action/action.show.js b/src/core/action/action.show.js index 68296ae19..34903513e 100644 --- a/src/core/action/action.show.js +++ b/src/core/action/action.show.js @@ -4,16 +4,19 @@ * @class BI.ShowAction * @extends BI.Action */ -BI.ShowAction = BI.inherit(BI.Action, { - actionPerformed: function (src, tar, callback) { +import Action from "./action"; +export default class ShowAction extends Action { + actionPerformed(src, tar, callback) { tar = tar || this.options.tar; tar.setVisible(true); callback && callback(); - }, + } - actionBack: function (tar, src, callback) { + actionBack(tar, src, callback) { tar = tar || this.options.tar; tar.setVisible(false); callback && callback(); } -}); +} + +BI.extend(BI, { ShowAction }); diff --git a/src/core/behavior/0.behavior.js b/src/core/behavior/0.behavior.js index 3645f87b7..dcd82a58d 100644 --- a/src/core/behavior/0.behavior.js +++ b/src/core/behavior/0.behavior.js @@ -19,14 +19,17 @@ BI.BehaviorFactory = { * @class BI.Behavior * @extends BI.OB */ -BI.Behavior = BI.inherit(BI.OB, { - _defaultConfig: function () { - return BI.extend(BI.Behavior.superclass._defaultConfig.apply(this, arguments), { - rule: function () {return true;} + +import OB from "../3.ob"; +export default class Behavior extends OB { + _defaultConfig() { + return BI.extend(super._defaultConfig(arguments), { + rule: () => true }); - }, + } - doBehavior: function () { + doBehavior() { } -}); +} +BI.extend(BI, { Behavior }); diff --git a/src/core/behavior/behavior.highlight.js b/src/core/behavior/behavior.highlight.js index 683bc061e..de7306c49 100644 --- a/src/core/behavior/behavior.highlight.js +++ b/src/core/behavior/behavior.highlight.js @@ -4,13 +4,14 @@ * @class BI.HighlightBehavior * @extends BI.Behavior */ -BI.HighlightBehavior = BI.inherit(BI.Behavior, { - doBehavior: function (items) { - var args = Array.prototype.slice.call(arguments, 1), +import Behavior from "./0.behavior"; +export default class HighlightBehavior extends Behavior { + doBehavior(items) { + const args = Array.prototype.slice.call(arguments, 1), o = this.options; BI.each(items, function (i, item) { if (item instanceof BI.Single) { - var rule = o.rule(item.getValue(), item); + const rule = o.rule(item.getValue(), item); function doBe (run) { if (run === true) { @@ -30,4 +31,5 @@ BI.HighlightBehavior = BI.inherit(BI.Behavior, { } }); } -}); +} +BI.extend(BI, { HighlightBehavior }); diff --git a/src/core/behavior/behavior.redmark.js b/src/core/behavior/behavior.redmark.js index b9c6572e9..e59cde9f3 100644 --- a/src/core/behavior/behavior.redmark.js +++ b/src/core/behavior/behavior.redmark.js @@ -4,9 +4,10 @@ * @class BI.RedMarkBehavior * @extends BI.Behavior */ -BI.RedMarkBehavior = BI.inherit(BI.Behavior, { - doBehavior: function (items) { - var args = Array.prototype.slice.call(arguments, 1), +import Behavior from "./0.behavior"; +export default class RedMarkBehavior extends Behavior { + doBehavior(items) { + const args = Array.prototype.slice.call(arguments, 1), o = this.options; BI.each(items, function (i, item) { if(item instanceof BI.Single) { @@ -20,4 +21,5 @@ BI.RedMarkBehavior = BI.inherit(BI.Behavior, { } }); } -}); +} +BI.extend(BI, { RedMarkBehavior }) diff --git a/src/core/controller/0.controller.js b/src/core/controller/0.controller.js index 4eba2c0ad..fd79f532d 100644 --- a/src/core/controller/0.controller.js +++ b/src/core/controller/0.controller.js @@ -6,6 +6,8 @@ * @extends BI.OB * @abstract */ -BI.Controller = BI.inherit(BI.OB, { -}); -BI.Controller.EVENT_CHANGE = "__EVENT_CHANGE__"; +import OB from "../3.ob"; +export default class Controller extends OB { + static EVENT_CHANGE = "__EVENT_CHANGE__"; +} +BI.extend(BI, { Controller }) diff --git a/src/core/controller/controller.broadcast.js b/src/core/controller/controller.broadcast.js index 71d7330c7..8cb4db3a3 100644 --- a/src/core/controller/controller.broadcast.js +++ b/src/core/controller/controller.broadcast.js @@ -4,35 +4,28 @@ * Created by GUY on 2015/12/23. * @class */ -BI.BroadcastController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class BroadcastController extends Controller { + init() { this._broadcasts = {}; - }, + } - on: function (name, fn) { - var self = this; + on(name, fn) { if (!this._broadcasts[name]) { this._broadcasts[name] = []; } this._broadcasts[name].push(fn); - return function () { - self.remove(name, fn); - }; - }, + return () => this.remove(name, fn); + } - send: function (name) { - var args = [].slice.call(arguments, 1); - BI.each(this._broadcasts[name], function (i, fn) { - fn.apply(null, args); - }); - }, + send(name) { + const args = [].slice.call(arguments, 1); + BI.each(this._broadcasts[name], (i, fn) => fn.apply(null, args)); + } - remove: function (name, fn) { - var self = this; + remove(name, fn) { if (fn) { - BI.remove(this._broadcasts[name], function (index, cb) { - return fn === cb; - }); + BI.remove(this._broadcasts[name], (index, cb) => fn === cb); if (this._broadcasts[name].length === 0) { delete this._broadcasts[name]; } @@ -41,4 +34,5 @@ BI.BroadcastController = BI.inherit(BI.Controller, { } return this; } -}); +} +BI.extend(BI, { BroadcastController }) \ No newline at end of file diff --git a/src/core/controller/controller.bubbles.js b/src/core/controller/controller.bubbles.js index fa5cefb5f..fcdd69f4b 100644 --- a/src/core/controller/controller.bubbles.js +++ b/src/core/controller/controller.bubbles.js @@ -5,11 +5,12 @@ * Created by GUY on 2015/8/21. * @class */ -BI.BubblesController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class BubblesController extends Controller { + init() { this.storeBubbles = {}; this.storePoppers = {}; - }, + } /** * @@ -19,14 +20,14 @@ BI.BubblesController = BI.inherit(BI.Controller, { * @param offsetStyle center, left, right三种类型, 默认left * @returns {BI.BubblesController} */ - show: function (name, text, context, opt) { + show(name, text, context, opt) { opt || (opt = {}); - var container = opt.container || context; - var offsetStyle = opt.offsetStyle || "left"; - var level = opt.level || "error"; - var adjustYOffset = opt.adjustYOffset || 0; - var adjustXOffset = opt.adjustXOffset || 0; - // var fixed = opt.fixed !== false; + const container = opt.container || context; + const offsetStyle = opt.offsetStyle || "left"; + const level = opt.level || "error"; + const adjustYOffset = opt.adjustYOffset || 0; + const adjustXOffset = opt.adjustXOffset || 0; + // const fixed = opt.fixed !== false; if (!this.storeBubbles[name]) { this.storeBubbles[name] = BI.createWidget({ @@ -37,7 +38,7 @@ BI.BubblesController = BI.inherit(BI.Controller, { height: 18 }); } - var bubble = this.storeBubbles[name]; + const bubble = this.storeBubbles[name]; if (bubble.getText() !== text) { bubble.setText(text); } @@ -69,18 +70,18 @@ BI.BubblesController = BI.inherit(BI.Controller, { ] }); return this; - }, + } - hide: function (name) { + hide(name) { this.remove(name); return this; - }, + } - has: function (name) { + has(name) { return this.storeBubbles[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -88,17 +89,14 @@ BI.BubblesController = BI.inherit(BI.Controller, { this.storePoppers[name] && this.storePoppers[name].destroy(); delete this.storeBubbles[name]; return this; - }, + } - removeAll: function () { - BI.each(this.storeBubbles, function (name, bubble) { - bubble.destroy(); - }); - BI.each(this.storePoppers, function (name, popper) { - popper.destroy(); - }); + removeAll() { + BI.each(this.storeBubbles, (name, bubble) => bubble.destroy()); + BI.each(this.storePoppers, (name, popper) => popper.destroy()); this.storeBubbles = {}; this.storePoppers = {}; return this; } -}); +} +BI.extend(BI, { BubblesController }); diff --git a/src/core/controller/controller.drawer.js b/src/core/controller/controller.drawer.js index 68fdadbc8..d90c226f2 100644 --- a/src/core/controller/controller.drawer.js +++ b/src/core/controller/controller.drawer.js @@ -4,62 +4,61 @@ * @class BI.popoverController * @extends BI.Controller */ -BI.DrawerController = BI.inherit(BI.Controller, { - props: function () { - return { - modal: true, // 模态窗口 - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class DrawerController extends Controller { + props = { + modal: true, // 模态窗口 + render: "body" + } - init: function () { + init() { this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; this.floatContainer = {}; this.floatOpened = {}; this.zindexMap = {}; - }, + } - create: function (name, options, context) { + create(name, options, context) { if (this.has(name)) { return this; } - var popover = BI.createWidget(options || {}, { + const popover = BI.createWidget(options || {}, { type: "bi.drawer" }, context); this.add(name, popover, options, context); return this; - }, + } - open: function (name) { - var self = this, o = this.options; + open(name) { + const o = this.options; if (!this.has(name)) { return this; } if (!this.floatOpened[name]) { this.floatOpened[name] = true; - var container = this.floatContainer[name]; - var zIndex = BI.Popovers._getZIndex(); + const container = this.floatContainer[name]; + const zIndex = BI.Popovers._getZIndex(); container.element.css("zIndex", zIndex); this.modal && container.element.__hasZIndexMask__(this.zindexMap[name]) && container.element.__releaseZIndexMask__(this.zindexMap[name]); this.zindexMap[name] = zIndex; if (this.modal) { - var mask = container.element.__buildZIndexMask__(BI.Popovers._getZIndex()); - mask.click(function () { + const mask = container.element.__buildZIndexMask__(BI.Popovers._getZIndex()); + mask.click(() => { mask.destroy(); - self.get(name).close(); + this.get(name).close(); }); } this.get(name).setZindex(BI.Popovers._getZIndex()); this.floatContainer[name].visible(); - var popover = this.get(name); + const popover = this.get(name); popover.show && popover.show(); } return this; - }, + } - close: function (name) { + close(name) { if (!this.has(name)) { return this; } @@ -69,22 +68,21 @@ BI.DrawerController = BI.inherit(BI.Controller, { this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } return this; - }, + } - show: function (name) { + show(name) { return this.open(name); - }, + } - hide: function (name) { + hide(name) { return this.close(name); - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this.floatOpened[name] === true; - }, + } - add: function (name, popover, options, context) { - var self = this; + add(name, popover, options, context) { options || (options = {}); if (this.has(name)) { return this; @@ -105,9 +103,7 @@ BI.DrawerController = BI.inherit(BI.Controller, { }); this.floatManager[name] = popover; (function (key) { - popover.on(BI.Drawer.EVENT_CLOSE, function () { - self.close(key); - }); + popover.on(BI.Drawer.EVENT_CLOSE, () => this.close(key)); })(name); BI.createWidget({ type: "bi.absolute", @@ -121,17 +117,17 @@ BI.DrawerController = BI.inherit(BI.Controller, { }] }); return this; - }, + } - get: function (name) { + get(name) { return this.floatManager[name]; - }, + } - has: function (name) { + has(name) { return BI.isNotNull(this.floatManager[name]); - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -143,13 +139,12 @@ BI.DrawerController = BI.inherit(BI.Controller, { delete this.floatContainer[name]; delete this.floatOpened[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(this.floatContainer, function (name, container) { + removeAll() { + BI.each(this.floatContainer, (name, container) => { container.destroy(); - self.modal && self.floatContainer[name].element.__releaseZIndexMask__(self.zindexMap[name]); + this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); this.floatManager = {}; this.floatLayer = {}; @@ -158,4 +153,5 @@ BI.DrawerController = BI.inherit(BI.Controller, { this.zindexMap = {}; return this; } -}); +} +BI.extend(BI, { DrawerController }); diff --git a/src/core/controller/controller.layer.js b/src/core/controller/controller.layer.js index 6887603f7..d12c807d7 100644 --- a/src/core/controller/controller.layer.js +++ b/src/core/controller/controller.layer.js @@ -4,32 +4,31 @@ * Created by GUY on 2015/6/24. * @class */ -BI.LayerController = BI.inherit(BI.Controller, { - props: function () { - return { - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class LayerController extends Controller { + props = { + render: "body" + } - init: function () { + init() { this.layerManager = {}; this.layouts = {}; this.zindex = BI.zIndex_layer; - }, + } - _initResizer: function () { + _initResizer() { this.resizer = BI.Resizers.add("layerController" + BI.uniqueId(), BI.bind(this._resize, this)); - }, + } - _resize: function () { + _resize() { BI.each(this.layouts, function (i, layer) { if (layer.element.is(":visible")) { layer.element.trigger("__resize__"); } }); - }, + } - make: function (name, container, op, context) { + make(name, container, op, context) { if (BI.isWidget(container)) { op = op || {}; op.container = container; @@ -38,16 +37,16 @@ BI.LayerController = BI.inherit(BI.Controller, { op = container; } return this.create(name, null, op, context); - }, + } - create: function (name, from, op, context) { + create(name, from, op, context) { BI.isNull(this.resizer) && this._initResizer(); if (this.has(name)) { return this.get(name); } op || (op = {}); - var offset = op.offset || {}; - var w = from; + const offset = op.offset || {}; + let w = from; if (BI.isWidget(from)) { w = from.element; } @@ -57,10 +56,10 @@ BI.LayerController = BI.inherit(BI.Controller, { if (this.has(name)) { return this.get(name); } - var widget = BI.createWidget((op.render || {}), BI.extend({ + const widget = BI.createWidget((op.render || {}), BI.extend({ type: "bi.layout" }, op), context); - var layout = BI.createWidget({ + const layout = BI.createWidget({ type: "bi.absolute", invisible: true, items: [{ @@ -102,31 +101,31 @@ BI.LayerController = BI.inherit(BI.Controller, { } this.add(name, widget, layout); return widget; - }, + } - show: function (name, callback) { + show(name, callback) { if (!this.has(name)) { return this; } this._getLayout(name).visible(); this._getLayout(name).element.css("z-index", this.zindex++).show(0, callback).trigger("__resize__"); return this; - }, + } - hide: function (name, callback) { + hide(name, callback) { if (!this.has(name)) { return this; } this._getLayout(name).invisible(); this._getLayout(name).element.hide(0, callback); return this; - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this._getLayout(name).isVisible(); - }, + } - add: function (name, layer, layout) { + add(name, layer, layout) { if (this.has(name)) { throw new Error("不能创建同名的Layer"); } @@ -135,21 +134,21 @@ BI.LayerController = BI.inherit(BI.Controller, { this.layouts[name] = layout; layout.element.css("z-index", this.zindex++); return this; - }, + } - _getLayout: function (name) { + _getLayout(name) { return this.layouts[name]; - }, + } - get: function (name) { + get(name) { return this.layerManager[name]; - }, + } - has: function (name) { + has(name) { return this.layerManager[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -158,16 +157,16 @@ BI.LayerController = BI.inherit(BI.Controller, { delete this.layerManager[name]; delete this.layouts[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(BI.keys(this.layerManager), function (index, name) { - self.layerManager[name].destroy(); - self.layouts[name].destroy(); + removeAll() { + BI.each(BI.keys(this.layerManager), (index, name) => { + this.layerManager[name].destroy(); + this.layouts[name].destroy(); }); this.layerManager = {}; this.layouts = {}; return this; } -}); +} +BI.extend(BI, { LayerController }); diff --git a/src/core/controller/controller.masker.js b/src/core/controller/controller.masker.js index 0b55b0781..cda5be1e6 100644 --- a/src/core/controller/controller.masker.js +++ b/src/core/controller/controller.masker.js @@ -4,9 +4,11 @@ * Created by GUY on 2015/6/24. * @class */ -BI.MaskersController = BI.inherit(BI.LayerController, { - init: function () { - BI.MaskersController.superclass.init.apply(this, arguments); +import LayerController from "./controller.layer"; +export default class MaskersController extends LayerController { + init() { + super.init(arguments); this.zindex = BI.zIndex_masker; } -}); +} +BI.extend(BI, { MaskersController }); diff --git a/src/core/controller/controller.popover.js b/src/core/controller/controller.popover.js index 9e36e5849..08f40cf60 100644 --- a/src/core/controller/controller.popover.js +++ b/src/core/controller/controller.popover.js @@ -4,15 +4,14 @@ * @class BI.popoverController * @extends BI.Controller */ -BI.PopoverController = BI.inherit(BI.Controller, { - props: function () { - return { - modal: true, // 模态窗口 - render: "body" - }; - }, +import Controller from "./0.controller"; +export default class PopoverController extends Controller { + props = { + modal: true, // 模态窗口 + render: "body" + } - init: function () { + init() { this.modal = this.options.modal; this.floatManager = {}; this.floatLayer = {}; @@ -20,38 +19,38 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.floatOpened = {}; this.zindex = BI.zIndex_popover; this.zindexMap = {}; - }, + } - create: function (name, options, context) { + create(name, options, context) { if (this.has(name)) { return this; } - var popover = BI.createWidget(options || {}, { + const popover = BI.createWidget(options || {}, { type: "bi.popover" }, context); this.add(name, popover, options, context); return this; - }, + } - open: function (name) { + open(name) { if (!this.has(name)) { return this; } if (!this.floatOpened[name]) { this.floatOpened[name] = true; - var container = this.floatContainer[name]; + const container = this.floatContainer[name]; container.element.css("zIndex", this.zindex++); this.modal && container.element.__hasZIndexMask__(this.zindexMap[name]) && container.element.__releaseZIndexMask__(this.zindexMap[name]); this.zindexMap[name] = this.zindex; this.modal && container.element.__buildZIndexMask__(this.zindex++); this.get(name).setZindex(this.zindex++); this.floatContainer[name].visible(); - var popover = this.get(name); + const popover = this.get(name); popover.show && popover.show(); - var W = BI.Widget._renderEngine.createElement(this.options.render).width(), + const W = BI.Widget._renderEngine.createElement(this.options.render).width(), H = BI.Widget._renderEngine.createElement(this.options.render).height(); - var w = popover.element.width(), h = popover.element.height(); - var left = (W - w) / 2, top = (H - h) / 2; + const w = popover.element.width(), h = popover.element.height(); + const left = (W - w) / 2, top = (H - h) / 2; if (left < 0) { left = 0; } @@ -65,9 +64,9 @@ BI.PopoverController = BI.inherit(BI.Controller, { }); } return this; - }, + } - close: function (name) { + close(name) { if (!this.has(name)) { return this; } @@ -77,22 +76,21 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); } return this; - }, + } - show: function (name) { + show(name) { return this.open(name); - }, + } - hide: function (name) { + hide(name) { return this.close(name); - }, + } - isVisible: function (name) { + isVisible(name) { return this.has(name) && this.floatOpened[name] === true; - }, + } - add: function (name, popover, options, context) { - var self = this; + add(name, popover, options, context) { options || (options = {}); if (this.has(name)) { return this; @@ -113,9 +111,7 @@ BI.PopoverController = BI.inherit(BI.Controller, { }); this.floatManager[name] = popover; (function (key) { - popover.on(BI.Popover.EVENT_CLOSE, function () { - self.close(key); - }); + popover.on(BI.Popover.EVENT_CLOSE, () => self.close(key)); })(name); BI.createWidget({ type: "bi.absolute", @@ -129,17 +125,17 @@ BI.PopoverController = BI.inherit(BI.Controller, { }] }); return this; - }, + } - get: function (name) { + get(name) { return this.floatManager[name]; - }, + } - has: function (name) { + has(name) { return BI.isNotNull(this.floatManager[name]); - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } @@ -151,13 +147,12 @@ BI.PopoverController = BI.inherit(BI.Controller, { delete this.floatContainer[name]; delete this.floatOpened[name]; return this; - }, + } - removeAll: function () { - var self = this; - BI.each(this.floatContainer, function (name, container) { + removeAll() { + BI.each(this.floatContainer, (name, container) => { container.destroy(); - self.modal && self.floatContainer[name].element.__releaseZIndexMask__(self.zindexMap[name]); + this.modal && this.floatContainer[name].element.__releaseZIndexMask__(this.zindexMap[name]); }); this.floatManager = {}; this.floatLayer = {}; @@ -165,9 +160,10 @@ BI.PopoverController = BI.inherit(BI.Controller, { this.floatOpened = {}; this.zindexMap = {}; return this; - }, + } - _getZIndex: function () { + _getZIndex() { return this.zindex++; } -}); +} +BI.extend(BI, { PopoverController }); diff --git a/src/core/controller/controller.resizer.js b/src/core/controller/controller.resizer.js index 900bd3927..13eaa441e 100644 --- a/src/core/controller/controller.resizer.js +++ b/src/core/controller/controller.resizer.js @@ -4,25 +4,23 @@ * Created by GUY on 2015/6/24. * @class */ -BI.ResizeController = BI.inherit(BI.Controller, { +import Controller from "./0.controller"; +export default class ResizeController extends Controller { - init: function () { + init() { this.resizerManger = {}; - }, + } - _initResizeListener: function () { - var self = this; - this.resizeHandler = BI.debounce(function (ev) { - self._resize(ev); - }, 30); + _initResizeListener() { + this.resizeHandler = BI.debounce((ev) => this._resize(ev), 30); if ("onorientationchange" in _global) { _global.onorientationchange = this.resizeHandler; } else { BI.Widget._renderEngine.createElement(_global).resize(this.resizeHandler); } - }, + } - _resize: function (ev) { + _resize(ev) { BI.each(this.resizerManger, function (key, resizer) { if (resizer instanceof BI.$) { if (resizer.is(":visible")) { @@ -38,34 +36,33 @@ BI.ResizeController = BI.inherit(BI.Controller, { resizer(ev); } }); - }, + } - add: function (name, resizer) { - var self = this; + add(name, resizer) { BI.isNull(this.resizeHandler) && this._initResizeListener(); if (this.has(name)) { return this; } this.resizerManger[name] = resizer; - return function () { - self.remove(name); - }; - }, + return () => this.remove(name); + } - get: function (name) { + get(name) { return this.resizerManger[name]; - }, + } - has: function (name) { + has(name) { return this.resizerManger[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } delete this.resizerManger[name]; return this; } -}); +} + +BI.extend(BI, { ResizeController }); diff --git a/src/core/controller/controller.tooltips.js b/src/core/controller/controller.tooltips.js index 98f90fb0b..efc0a1517 100644 --- a/src/core/controller/controller.tooltips.js +++ b/src/core/controller/controller.tooltips.js @@ -6,11 +6,12 @@ * @class BI.TooltipsController * @extends BI.Controller */ -BI.TooltipsController = BI.inherit(BI.Controller, { - init: function () { +import Controller from "./0.controller"; +export default class TooltipsController extends Controller { + init() { this.tooltipsManager = {}; this.showingTips = {};// 存储正在显示的tooltip - }, + } /** * @@ -21,34 +22,31 @@ BI.TooltipsController = BI.inherit(BI.Controller, { * @returns {*} * @private */ - _createTooltip: function (opt) { + _createTooltip(opt) { return BI.createWidget({ type: "bi.tooltip", ...opt, stopEvent: true }); - }, + } // opt: {container: '', belowMouse: false} - show: function (e, name, tooltipOpt, context, opt) { + show(e, name, tooltipOpt, context, opt) { opt || (opt = {}); - var self = this; - BI.each(this.showingTips, function (i, tip) { - self.hide(i); - }); + BI.each(this.showingTips, (i, tip) => this.hide(i)); this.showingTips = {}; if (!this.has(name)) { this.create(name, tooltipOpt, document.fullscreenElement ? context : (opt.container || "body")); } if (!opt.belowMouse) { - var offset = context.element.offset(); - var bounds = context.element.bounds(); + const offset = context.element.offset(); + const bounds = context.element.bounds(); if (bounds.height === 0 || bounds.width === 0) { return; } - var top = offset.top + bounds.height + 5; + const top = offset.top + bounds.height + 5; } - var tooltip = this.get(name); + const tooltip = this.get(name); tooltip.element.css({ left: "0px", top: "0px" @@ -57,13 +55,13 @@ BI.TooltipsController = BI.inherit(BI.Controller, { tooltip.element.height(tooltip.element[0].scrollHeight); this.showingTips[name] = true; // scale影响要计算在内 - // var scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; - // var x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; - var x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; + // const scale = context.element.offset().left / context.element.get(0).getBoundingClientRect().left; + // const x = (e.pageX || e.clientX) * scale + 15, y = (e.pageY || e.clientY) * scale + 15; + const x = (e.pageX || e.clientX) + 15, y = (e.pageY || e.clientY) + 15; if (x + tooltip.element.outerWidth() > BI.Widget._renderEngine.createElement("body").outerWidth()) { x -= tooltip.element.outerWidth() + 15; } - var bodyHeight = BI.Widget._renderEngine.createElement("body").outerHeight(); + const bodyHeight = BI.Widget._renderEngine.createElement("body").outerHeight(); if (y + tooltip.element.outerHeight() > bodyHeight || top + tooltip.element.outerHeight() > bodyHeight) { y -= tooltip.element.outerHeight() + 15; !opt.belowMouse && (y = Math.min(y, offset.top - tooltip.element.outerHeight() - 5)); @@ -75,14 +73,14 @@ BI.TooltipsController = BI.inherit(BI.Controller, { left: x < 0 ? 0 : x + "px", top: y < 0 ? 0 : y + "px" }); - tooltip.element.hover(function () { - self.remove(name); + tooltip.element.hover(() => { + this.remove(name); context.element.trigger("mouseleave.title" + context.getName()); }); return this; - }, + } - hide: function (name, callback) { + hide(name, callback) { if (!this.has(name)) { return this; } @@ -90,11 +88,11 @@ BI.TooltipsController = BI.inherit(BI.Controller, { this.get(name).element.hide(0, callback); this.get(name).invisible(); return this; - }, + } - create: function (name, tooltipOpt, context) { + create(name, tooltipOpt, context) { if (!this.has(name)) { - var tooltip = this._createTooltip(tooltipOpt); + const tooltip = this._createTooltip(tooltipOpt); this.add(name, tooltip); BI.createWidget({ type: "bi.absolute", @@ -106,38 +104,38 @@ BI.TooltipsController = BI.inherit(BI.Controller, { tooltip.invisible(); } return this.get(name); - }, + } - add: function (name, bubble) { + add(name, bubble) { if (this.has(name)) { return this; } this.set(name, bubble); return this; - }, + } - get: function (name) { + get(name) { return this.tooltipsManager[name]; - }, + } - set: function (name, bubble) { + set(name, bubble) { this.tooltipsManager[name] = bubble; - }, + } - has: function (name) { + has(name) { return this.tooltipsManager[name] != null; - }, + } - remove: function (name) { + remove(name) { if (!this.has(name)) { return this; } this.tooltipsManager[name].destroy(); delete this.tooltipsManager[name]; return this; - }, + } - removeAll: function () { + removeAll() { BI.each(this.tooltipsManager, function (name, tooltip) { tooltip.destroy(); }); @@ -145,4 +143,5 @@ BI.TooltipsController = BI.inherit(BI.Controller, { this.showingTips = {}; return this; } -}); +} +BI.extend(BI, { TooltipsController });