funcBehavior.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * 过滤对象的函数属性
  3. * @param {Object} opts
  4. */
  5. const mergeOptionsToData = (opts = {}) => {
  6. const options = Object.assign({}, opts)
  7. for (const key in options) {
  8. if (options.hasOwnProperty(key) && typeof options[key] === 'function') {
  9. delete options[key]
  10. }
  11. }
  12. return options
  13. }
  14. /**
  15. * Simple bind, faster than native
  16. *
  17. * @param {Function} fn
  18. * @param {Object} ctx
  19. * @return {Function}
  20. */
  21. const bind = (fn, ctx) => {
  22. return (...args) => {
  23. return args.length ? fn.apply(ctx, args) : fn.call(ctx)
  24. }
  25. }
  26. /**
  27. * Object assign
  28. */
  29. const assign = (...args) => Object.assign({}, ...args)
  30. export default Behavior({
  31. definitionFilter(defFields) {
  32. defFields.data = mergeOptionsToData(defFields.data)
  33. defFields.data.in = false
  34. defFields.data.visible = false
  35. },
  36. methods: {
  37. /**
  38. * 过滤对象的函数属性
  39. * @param {Object} opts
  40. */
  41. $$mergeOptionsToData: mergeOptionsToData,
  42. /**
  43. * 合并参数并绑定方法
  44. *
  45. * @param {Object} opts 参数对象
  46. * @param {Object} fns 方法挂载的属性
  47. */
  48. $$mergeOptionsAndBindMethods (opts = {}, fns = this.fns) {
  49. const options = Object.assign({}, opts)
  50. for (const key in options) {
  51. if (options.hasOwnProperty(key) && typeof options[key] === 'function') {
  52. fns[key] = bind(options[key], this)
  53. delete options[key]
  54. }
  55. }
  56. return options
  57. },
  58. /**
  59. * Promise setData
  60. * @param {Array} args 参数对象
  61. */
  62. $$setData (...args) {
  63. const params = assign({}, ...args)
  64. return new Promise((resolve) => {
  65. this.setData(params, resolve)
  66. })
  67. },
  68. /**
  69. * 延迟指定时间执行回调函数
  70. * @param {Function} callback 回调函数
  71. * @param {Number} timeout 延迟时间
  72. */
  73. $$requestAnimationFrame (callback = () => {}, timeout = 1000 / 60) {
  74. return new Promise((resolve) => setTimeout(resolve, timeout)).then(callback)
  75. },
  76. },
  77. /**
  78. * 组件生命周期函数,在组件实例进入页面节点树时执行
  79. */
  80. created () {
  81. this.fns = {}
  82. },
  83. /**
  84. * 组件生命周期函数,在组件实例被从页面节点树移除时执行
  85. */
  86. detached () {
  87. this.fns = {}
  88. },
  89. })