JS bridge

JS Bridge 通信原理
https://mp.weixin.qq.com/s/T78J3dM9i5TvLu0h6joX3A

操作class

  1. // 查询class
  2. export const hasClass = function(obj, cls) {
  3. return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  4. };
  5. // 添加class
  6. export const addClass = function(obj, cls) {
  7. if (!hasClass(obj, cls)) obj.className += ' ' + cls;
  8. };
  9. // 移除class
  10. export const removeClass = function(obj, cls) {
  11. if (hasClass(obj, cls)) {
  12. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  13. obj.className = obj.className.replace(reg, ' ');
  14. }
  15. };
  16. // class切换
  17. export const toggleClass = function(obj, cls) {
  18. if (hasClass(obj, cls)) {
  19. removeClass(obj, cls);
  20. } else {
  21. addClass(obj, cls);
  22. }
  23. };

js 判断

  1. // 判断是null or undefined or ''
  2. export const isEmpty = function (val) {
  3. // null or undefined
  4. if (val == null) return true
  5. if (typeof val === 'boolean') return false
  6. if (typeof val === 'number') return !val
  7. if (val instanceof Error) return val.message === ''
  8. switch (Object.prototype.toString.call(val)) {
  9. // String or Array
  10. case '[object String]':
  11. case '[object Array]':
  12. return !val.length
  13. // Map or Set or File
  14. case '[object File]':
  15. case '[object Map]':
  16. case '[object Set]': {
  17. return !val.size
  18. }
  19. // Plain Object
  20. case '[object Object]': {
  21. return !Object.keys(val).length
  22. }
  23. }
  24. return false
  25. }
  26. export function isString(obj) {
  27. return Object.prototype.toString.call(obj) === '[object String]'
  28. }
  29. export function isObject(obj) {
  30. return Object.prototype.toString.call(obj) === '[object Object]'
  31. }
  32. export function isArray(value) {
  33. return value instanceof Array
  34. }
  35. export function isHtmlElement(node) {
  36. return node && node.nodeType === Node.ELEMENT_NODE
  37. }
  38. export const isFunction = (functionToCheck) => {
  39. var getType = {}
  40. return (
  41. functionToCheck &&
  42. getType.toString.call(functionToCheck) === '[object Function]'
  43. )
  44. }
  45. export const isUndefined = (val) => {
  46. // eslint-disable-next-line no-void
  47. return val === void 0
  48. }
  49. export const isDefined = (val) => {
  50. return val !== undefined && val !== null
  51. }
  52. // 是否相等
  53. // 数组、字符串、数字(对象不行)
  54. export const valueEquals = (a, b) => {
  55. // see: https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript
  56. if (a === b) return true
  57. if (!(a instanceof Array)) return false
  58. if (!(b instanceof Array)) return false
  59. if (a.length !== b.length) return false
  60. for (let i = 0; i !== a.length; ++i) {
  61. if (a[i] !== b[i]) return false
  62. }
  63. return true
  64. }