-
Notifications
You must be signed in to change notification settings - Fork 1
/
can-simple-observable.js
103 lines (93 loc) · 2.43 KB
/
can-simple-observable.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"use strict";
var log = require("./log");
var ns = require("can-namespace");
var canSymbol = require("can-symbol");
var canReflect = require("can-reflect");
var ObservationRecorder = require("can-observation-recorder");
var valueEventBindings = require("can-event-queue/value/value");
var dispatchSymbol = canSymbol.for("can.dispatch");
/**
* @module {function} can-simple-observable
* @parent can-observables
* @collection can-infrastructure
* @package ./package.json
* @description Create an observable value.
*
* @signature `new SimpleObservable(initialValue)`
*
* Creates an observable value that can be read, written, and observed using [can-reflect].
*
* @param {*} initialValue The initial value of the observable.
*
* @return {can-simple-observable} An observable instance
*
* @body
*
* ## Use
*
* ```js
* var obs = new SimpleObservable('one');
*
* canReflect.getValue(obs); // -> "one"
*
* canReflect.setValue(obs, 'two');
* canReflect.getValue(obs); // -> "two"
*
* function handler(newValue) {
* // -> "three"
* };
* canReflect.onValue(obs, handler);
* canReflect.setValue(obs, 'three');
*
* canReflect.offValue(obs, handler);
* ```
*/
function SimpleObservable(initialValue) {
this._value = initialValue;
}
// mix in the value-like object event bindings
valueEventBindings(SimpleObservable.prototype);
canReflect.assignMap(SimpleObservable.prototype, {
log: log,
get: function(){
ObservationRecorder.add(this);
return this._value;
},
set: function(value){
var old = this._value;
this._value = value;
this[dispatchSymbol](value, old);
}
});
Object.defineProperty(SimpleObservable.prototype,"value",{
set: function(value){
return this.set(value);
},
get: function(){
return this.get();
}
});
var simpleObservableProto = {
"can.getValue": SimpleObservable.prototype.get,
"can.setValue": SimpleObservable.prototype.set,
"can.isMapLike": false,
"can.valueHasDependencies": function(){
return true;
}
};
//!steal-remove-start
if (process.env.NODE_ENV !== 'production') {
simpleObservableProto["can.getName"] = function() {
var value = this._value;
if (typeof value !== 'object' || value === null) {
value = JSON.stringify(value);
}
else {
value = '';
}
return canReflect.getName(this.constructor) + "<" + value + ">";
};
}
//!steal-remove-end
canReflect.assignSymbols(SimpleObservable.prototype, simpleObservableProto);
module.exports = ns.SimpleObservable = SimpleObservable;