1. // 当前 Dep 的 id,唯一
    2. let uid = 0
    3. /**
    4. * A dep is an observable that can have multiple
    5. * directives subscribing to it.
    6. */
    7. export default class Dep {
    8. static target: ?Watcher;
    9. id: number;
    10. subs: Array<Watcher>;
    11. constructor () {
    12. // 当前 Dep 的 id,唯一
    13. this.id = uid++
    14. // 监听者列表
    15. this.subs = []
    16. }
    17. // 添加监听者
    18. addSub (sub: Watcher) {
    19. this.subs.push(sub)
    20. }
    21. // 移除监听
    22. removeSub (sub: Watcher) {
    23. remove(this.subs, sub)
    24. }
    25. // 依赖收集,双向收集,目的是为了保持一致性
    26. depend () {
    27. if (Dep.target) {
    28. Dep.target.addDep(this)
    29. }
    30. }
    31. // 通知依赖项响应
    32. notify () {
    33. // stabilize the subscriber list first
    34. // 浅拷贝,用于可能的数据处理
    35. const subs = this.subs.slice()
    36. if (process.env.NODE_ENV !== 'production' && !config.async) {
    37. // subs aren't sorted in scheduler if not running async
    38. // we need to sort them now to make sure they fire in correct
    39. // order
    40. subs.sort((a, b) => a.id - b.id)
    41. }
    42. // 通知监听者响应
    43. for (let i = 0, l = subs.length; i < l; i++) {
    44. subs[i].update()
    45. }
    46. }
    47. }
    48. // The current target watcher being evaluated.
    49. // This is globally unique because only one watcher
    50. // can be evaluated at a time.
    51. Dep.target = null
    52. const targetStack = []
    53. export function pushTarget (target: ?Watcher) {
    54. targetStack.push(target)
    55. Dep.target = target
    56. }
    57. export function popTarget () {
    58. targetStack.pop()
    59. Dep.target = targetStack[targetStack.length - 1]
    60. }