b23138235bc0717e64b2360c366f2894b855b51faabd8e385539c4d500546c2c3f189a449e77cd34b474bcd6902f8ccb8031e47700160b90d1cd572106bd48 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* @flow */
  2. import type Watcher from './watcher'
  3. import { remove } from '../util/index'
  4. import config from '../config'
  5. let uid = 0
  6. /**
  7. * A dep is an observable that can have multiple
  8. * directives subscribing to it.
  9. */
  10. export default class Dep {
  11. static target: ?Watcher;
  12. id: number;
  13. subs: Array<Watcher>;
  14. constructor () {
  15. this.id = uid++
  16. this.subs = []
  17. }
  18. addSub (sub: Watcher) {
  19. this.subs.push(sub)
  20. }
  21. removeSub (sub: Watcher) {
  22. remove(this.subs, sub)
  23. }
  24. depend () {
  25. if (Dep.target) {
  26. Dep.target.addDep(this)
  27. }
  28. }
  29. notify () {
  30. // stabilize the subscriber list first
  31. const subs = this.subs.slice()
  32. if (process.env.NODE_ENV !== 'production' && !config.async) {
  33. // subs aren't sorted in scheduler if not running async
  34. // we need to sort them now to make sure they fire in correct
  35. // order
  36. subs.sort((a, b) => a.id - b.id)
  37. }
  38. for (let i = 0, l = subs.length; i < l; i++) {
  39. subs[i].update()
  40. }
  41. }
  42. }
  43. // The current target watcher being evaluated.
  44. // This is globally unique because only one watcher
  45. // can be evaluated at a time.
  46. Dep.target = null
  47. const targetStack = []
  48. export function pushTarget (target: ?Watcher) {
  49. targetStack.push(target)
  50. Dep.target = target
  51. }
  52. export function popTarget () {
  53. targetStack.pop()
  54. Dep.target = targetStack[targetStack.length - 1]
  55. }