observerHandle.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const equals = function(x, y) {
  2. if (x === y) {
  3. return true
  4. }
  5. if (!(x instanceof Object) || !(y instanceof Object)) {
  6. return false
  7. }
  8. if (x.constructor !== y.constructor) {
  9. return false
  10. }
  11. for (const p in x) {
  12. if (x.hasOwnProperty(p)) {
  13. if (!y.hasOwnProperty(p)) {
  14. return false
  15. }
  16. if (x[p] === y[p]) {
  17. continue
  18. }
  19. if (typeof x[p] !== 'object') {
  20. return false
  21. }
  22. if (!equals(x[p], y[p])) {
  23. return false
  24. }
  25. }
  26. }
  27. for (const p in y) {
  28. if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
  29. return false
  30. }
  31. }
  32. return true
  33. }
  34. function observerHandle(observerObj, args, that) {
  35. Object.keys(observerObj).forEach((obs) => {
  36. if (typeof observerObj[obs] === 'function') {
  37. let props
  38. if (args.props) {
  39. props = args.props
  40. }
  41. if (args[0]) {
  42. props = args[0]
  43. }
  44. if (!props) {
  45. return
  46. }
  47. if (!equals(props[obs], that.props[obs])) {
  48. observerObj[obs].call(that, that.props[obs], props[obs])
  49. }
  50. }
  51. })
  52. }
  53. function observersHandle(observersObj, args, that) {
  54. let preData = null
  55. if (Array.isArray(args)) {
  56. preData = args[1]
  57. } else {
  58. preData = args.props
  59. }
  60. Object.keys(observersObj).forEach((obs) => {
  61. let left = {}
  62. let right = {}
  63. if (obs.match(/\./)) {
  64. const _dataArr = obs.split('.')
  65. left = processChildAttr(preData, _dataArr)
  66. right = processChildAttr(that.data, _dataArr)
  67. } else {
  68. left = preData[obs]
  69. right = that.data[obs]
  70. }
  71. const dif = equals(left, right)
  72. if (!dif) {
  73. observersObj[obs].fn.call(that, ...observersObj[obs].arr)
  74. }
  75. })
  76. }
  77. function processChildAttr(attr, arr) {
  78. let _ = attr
  79. arr.forEach((name) => {
  80. _ = _[name]
  81. })
  82. return _
  83. }
  84. module.exports = {
  85. observerHandle,
  86. observersHandle,
  87. }