1 |
|
2 |
|
3 | import type Watcher from './watcher'
|
4 | import { remove } from '../util/index'
|
5 | import config from '../config'
|
6 |
|
7 | let uid = 0
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 | export default class Dep {
|
14 | static target: ?Watcher;
|
15 | id: number;
|
16 | subs: Array<Watcher>;
|
17 |
|
18 | constructor () {
|
19 | this.id = uid++
|
20 | this.subs = []
|
21 | }
|
22 |
|
23 | addSub (sub: Watcher) {
|
24 | this.subs.push(sub)
|
25 | }
|
26 |
|
27 | removeSub (sub: Watcher) {
|
28 | remove(this.subs, sub)
|
29 | }
|
30 |
|
31 | depend () {
|
32 | if (Dep.target) {
|
33 | Dep.target.addDep(this)
|
34 | }
|
35 | }
|
36 |
|
37 | notify () {
|
38 |
|
39 | const subs = this.subs.slice()
|
40 | if (process.env.NODE_ENV !== 'production' && !config.async) {
|
41 |
|
42 |
|
43 |
|
44 | subs.sort((a, b) => a.id - b.id)
|
45 | }
|
46 | for (let i = 0, l = subs.length; i < l; i++) {
|
47 | subs[i].update()
|
48 | }
|
49 | }
|
50 | }
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | Dep.target = null
|
56 | const targetStack = []
|
57 |
|
58 | export function pushTarget (target: ?Watcher) {
|
59 | targetStack.push(target)
|
60 | Dep.target = target
|
61 | }
|
62 |
|
63 | export function popTarget () {
|
64 | targetStack.pop()
|
65 | Dep.target = targetStack[targetStack.length - 1]
|
66 | }
|