Last active
November 18, 2016 20:28
-
-
Save mweststrate/3ef163608d35bcdfc41361c459806ca0 to your computer and use it in GitHub Desktop.
MobX 3: creating observables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pseudo code proposal to give more fine grained control and cleaning up the way in which observables are constructed in MobX | |
// Strategies | |
Strategy.Reference = "Reference" | |
Strategy.Deep = "Deep" | |
Strategy.Shallow = "Shallow" | |
Strategy.Structure = "AsStructure" | |
// The essen of MobX: trackable boxed values: | |
function createBoxedObservable(initialValue, strategy = Reference) { | |
return { | |
value: null, | |
set: newValue => { | |
switch (strategy) { | |
Reference: this.value = newValue | |
Deep: this.value = create(newValue, Deep) | |
Shallow: this.value = create(newValue, Reference) | |
Structure: this.value = deepEqual(this.value, newValue) ? this.value : newValue | |
} | |
}, | |
get: () => this.value | |
} | |
this.set(initialValue), | |
} | |
// Necessary to create observable objects: use a boxed observable as property | |
function createObservableProperty(target, name, boxedObservable) { | |
Object.defineProperty(target, name, { | |
get: boxedObservable.get | |
set: boxedObservable.set | |
}) | |
} | |
function extend(target, properties, defaultStrategy = Shallow) { | |
for (key, value in properties) | |
createObservableProperty(target, key, createBoxedObservable(value, getCustomStrategyForProp(key) || defaultStrategy)) | |
} | |
function create(thing, childStrategy?) { | |
if (thing is Observable) | |
return thing | |
if (thing is Array) | |
return new ObservableArray(thing.map(value => create(value, childStrategy || Reference))) | |
// Map, similar to array | |
if (thing is Object) | |
return extend({}, thing, childStrategy || Shallow) | |
if (thing is Primitive) | |
return createBoxedObservable(thing, childStrategy) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see mobxjs/mobx#649 (comment) for related thread