safeSetDataBehavior.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. export default Behavior({
  2. lifetimes: {
  3. created() {
  4. this.nextCallback = null
  5. },
  6. detached() {
  7. this.cancelNextCallback()
  8. },
  9. },
  10. methods: {
  11. /**
  12. * safeSetData
  13. * @param {Object} nextData 数据对象
  14. * @param {Function} callback 回调函数
  15. */
  16. safeSetData(nextData, callback) {
  17. this.pendingData = Object.assign({}, this.data, nextData)
  18. callback = this.setNextCallback(callback)
  19. this.setData(nextData, () => {
  20. this.pendingData = null
  21. callback()
  22. })
  23. },
  24. /**
  25. * 设置下一回调函数
  26. * @param {Function} callback 回调函数
  27. */
  28. setNextCallback(callback) {
  29. let active = true
  30. this.nextCallback = (event) => {
  31. if (active) {
  32. active = false
  33. this.nextCallback = null
  34. callback.call(this, event)
  35. }
  36. }
  37. this.nextCallback.cancel = () => {
  38. active = false
  39. }
  40. return this.nextCallback
  41. },
  42. /**
  43. * 取消下一回调函数
  44. */
  45. cancelNextCallback() {
  46. if (this.nextCallback !== null) {
  47. this.nextCallback.cancel()
  48. this.nextCallback = null
  49. }
  50. },
  51. },
  52. })