-
Notifications
You must be signed in to change notification settings - Fork 4
/
put.js
38 lines (29 loc) · 1.06 KB
/
put.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
var addListener = require("./add-listener.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js");
module.exports = put
// `obs.put` is a mutable implementation of `array[index] = value`
// that mutates both `list` and the internal `valueList` that
// is the current value of `obs` itself
function put(index, value) {
var obs = this
var valueList = obs().slice()
var originalLength = valueList.length
valueList[index] = typeof value === "function" ? value() : value
obs._list[index] = value
// remove past value listener if was observ
var removeListener = obs._removeListeners[index]
if (removeListener){
removeListener()
}
// add listener to value if observ
obs._removeListeners[index] = typeof value === "function" ?
addListener(obs, value) :
null
// fake splice diff
var valueArgs = index < originalLength ?
[index, 1, valueList[index]] :
[index, 0, valueList[index]]
setNonEnumerable(valueList, "_diff", [valueArgs])
obs._observSet(valueList)
return value
}