relationsBehavior.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import isEmpty from './isEmpty'
  2. import debounce from './debounce'
  3. /**
  4. * bind func to obj
  5. */
  6. function bindFunc(obj, method, observer) {
  7. const oldFn = obj[method]
  8. obj[method] = function(target) {
  9. if (observer) {
  10. observer.call(this, target, {
  11. [method]: true,
  12. })
  13. }
  14. if (oldFn) {
  15. oldFn.call(this, target)
  16. }
  17. }
  18. }
  19. // default methods
  20. const methods = ['linked', 'linkChanged', 'unlinked']
  21. // extra props
  22. const extProps = ['observer']
  23. module.exports = Behavior({
  24. lifetimes: {
  25. created() {
  26. this._debounce = null
  27. },
  28. },
  29. definitionFilter(defFields) {
  30. const { relations } = defFields
  31. if (!isEmpty(relations)) {
  32. for (const key in relations) {
  33. const relation = relations[key]
  34. // bind func
  35. methods.forEach((method) => bindFunc(relation, method, relation.observer))
  36. // delete extProps
  37. extProps.forEach((prop) => delete relation[prop])
  38. }
  39. }
  40. defFields.methods = defFields.methods || {}
  41. defFields.methods.debounce = function(func, wait = 0, immediate = false) {
  42. return (this._debounce = this._debounce || debounce(func.bind(this), wait, immediate)).call(this)
  43. }
  44. },
  45. })