您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

relationsBehavior.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import isEmpty from './isEmpty'
  2. import debounce from './debounce'
  3. import throttle from './throttle'
  4. /**
  5. * bind func to obj
  6. */
  7. function bindFunc(obj, method, observer) {
  8. const oldFn = obj[method]
  9. obj[method] = function(target) {
  10. if (observer) {
  11. observer.call(this, target, {
  12. [method]: true,
  13. })
  14. }
  15. if (oldFn) {
  16. oldFn.call(this, target)
  17. }
  18. }
  19. }
  20. // default methods
  21. const methods = ['linked', 'linkChanged', 'unlinked']
  22. // extra props
  23. const extProps = ['observer']
  24. export default Behavior({
  25. lifetimes: {
  26. created() {
  27. this.useThrottleFn = function (fn, wait = 0, options) {
  28. const throttled = throttle(fn.bind(this), wait, options)
  29. this._throttledFns.push(throttled)
  30. return {
  31. run: throttled,
  32. cancel: throttled.cancel,
  33. flush: throttled.flush,
  34. }
  35. }
  36. this._throttledFns = []
  37. this.callDebounceFn = function(fn, wait = 0, options) {
  38. return (this._debounced = this._debounced || debounce(fn.bind(this), wait, options)).call(this)
  39. }
  40. this._debounced = null
  41. },
  42. detached() {
  43. if (this._debounced && this._debounced.cancel) {
  44. this._debounced.cancel()
  45. }
  46. if (this._throttledFns.length > 0) {
  47. this._throttledFns.forEach((throttled) => {
  48. throttled.cancel()
  49. })
  50. this._throttledFns = []
  51. }
  52. },
  53. },
  54. definitionFilter(defFields) {
  55. const { relations } = defFields
  56. if (!isEmpty(relations)) {
  57. for (const key in relations) {
  58. const relation = relations[key]
  59. // bind func
  60. methods.forEach((method) => bindFunc(relation, method, relation.observer))
  61. // delete extProps
  62. extProps.forEach((prop) => delete relation[prop])
  63. }
  64. }
  65. Object.assign(defFields.methods = (defFields.methods || {}), {
  66. getRelationsName: function(types = ['parent', 'child', 'ancestor', 'descendant']) {
  67. return Object.keys(relations || {}).map((key) => {
  68. if (relations[key] && types.includes(relations[key].type)) {
  69. return key
  70. }
  71. return null
  72. }).filter((v) => !!v)
  73. },
  74. })
  75. },
  76. })