UNPKG

1.38 kBJavaScriptView Raw
1/* @flow */
2
3import type Watcher from './watcher'
4import { remove } from '../util/index'
5import config from '../config'
6
7let uid = 0
8
9/**
10 * A dep is an observable that can have multiple
11 * directives subscribing to it.
12 */
13export 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 // stabilize the subscriber list first
39 const subs = this.subs.slice()
40 if (process.env.NODE_ENV !== 'production' && !config.async) {
41 // subs aren't sorted in scheduler if not running async
42 // we need to sort them now to make sure they fire in correct
43 // order
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// The current target watcher being evaluated.
53// This is globally unique because only one watcher
54// can be evaluated at a time.
55Dep.target = null
56const targetStack = []
57
58export function pushTarget (target: ?Watcher) {
59 targetStack.push(target)
60 Dep.target = target
61}
62
63export function popTarget () {
64 targetStack.pop()
65 Dep.target = targetStack[targetStack.length - 1]
66}