mixin.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import Cursor from './cursor'
  2. export default {
  3. /**
  4. * Patch the instance's data function so that we can
  5. * directly bind to cursors in the `data` option.
  6. */
  7. init () {
  8. const dataFn = this.$options.data
  9. if (dataFn) {
  10. this.$options.data = () => {
  11. const raw = dataFn()
  12. Object.keys(raw).forEach(key => {
  13. const val = raw[key]
  14. if (val instanceof Cursor) {
  15. raw[key] = val.get()
  16. if (val.cb) {
  17. throw new Error(
  18. '[vue-store] A vue-store can only be subscribed to once.'
  19. )
  20. }
  21. val.subscribe(value => {
  22. this[key] = value
  23. })
  24. if (!this._vue_store_cursors) {
  25. this._vue_store_cursors = []
  26. }
  27. this._vue_store_cursors.push(val)
  28. }
  29. })
  30. return raw
  31. }
  32. }
  33. },
  34. /**
  35. * Dispose cursors owned by this instance.
  36. */
  37. beforeDestroy () {
  38. if (this._vue_store_cursors) {
  39. this._vue_store_cursors.forEach(c => c.dispose())
  40. }
  41. }
  42. }