/
object.js
68 lines (54 loc) · 1.63 KB
/
object.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var Observ = require('mutant/value')
var watch = require('mutant/watch')
var ObservAudioBuffer = require('lib/observ-audio-buffer')
var Path = require('path')
var computed = require('mutant/computed')
module.exports = ObservAudioBufferCached
var cachePerContext = new global.WeakMap()
function ObservAudioBufferCached (context) {
var obs = Observ({})
obs.currentValue = Observ()
obs.cuePoints = Observ()
var cache = cachePerContext.get(context.audio)
if (!cache) {
cache = {}
cachePerContext.set(context.audio, cache)
}
var release = null
var src = computed(obs, descriptor => descriptor.src)
var path = computed([context.cwd, src], (a, b) => a && b && Path.resolve(a, b) || null)
var unwatch = watch(path, update)
obs.destroy = function () {
unwatch()
update(null)
}
return obs
// scoped
function update (path) {
release && release()
release = null
if (path) {
var instance = cache[path]
if (!instance) {
instance = cache[path] = ObservAudioBuffer(context)
instance.listeners = []
instance.set(obs())
}
var releaseResolved = watch(instance.currentValue, obs.currentValue.set)
var releaseCuePoints = watch(instance.cuePoints, obs.cuePoints.set)
instance.listeners.push(obs)
release = function () {
releaseResolved()
releaseCuePoints()
instance.listeners.splice(instance.listeners.indexOf(obs), 1)
if (instance.listeners.length === 0) {
instance.destroy()
delete cache[path]
}
}
} else {
obs.currentValue.set(null)
obs.cuePoints.set(null)
}
}
}