构建observable 的 object
本文是 [mobx 源码初步认识] 第一篇
本系列文章全部采用 mobx 较新版本:[v6.2.0]
技术前提
在阅读之前,希望你对以下技术有所了解或实践,不然可能会影响你对本文的理解
ES6 装饰器:decorator
ES6 代理:proxy
ES6 反射:reflect
定义对象属性:Object.defineProperty
实现简易版 观察者模式
准备
一、目录结构
├── src
│ ├── api // 进行劫持方法和作出反应的 api
│ ├── core // 全局状态、函数等
│ ├── types // 重写关于 object,array 等类型的 api
│ ├── utils // 工具方法
│ ├── internal.ts
│ └── mobx.ts // 全局导出
└── package.json
二、劫持原理
两个关键词:属性劫持,递归
属性劫持,可以理解为是在编程语言层面上进行编程,这点在
proxy & reflect
中体现的尤为明显通过
Object.defineProperty
或proxy
可以实现在获取或修改对象属性时,做一些额外的操作mobx5,mobx6 版本默认劫持重构为了
proxy
,主要是proxy
相对于Object.defineProperty
较稳定,并且劫持的手段更多对象的属性值可能也是个对象或数组,那么如果是引用类型就进行递归劫持
三、整体步骤(本文先只讨论劫持对象)
先对整体步骤有个大概的了解,方便后面的理解
- 处理装饰器,准备好装饰器所需的参数
装饰器书写有带括号和不带括号的,但最后都要求返回 descriptor
@observable obj ...
@log({ name: 'aa' }) obj2 ...
- 劫持对象当前层的属性
根据属性值的类型,调用的相应 enhancer(即劫持器,后面会说到)进行劫持
- 递归劫持
判断是否为引用类型,如果是,则递归劫持
- 暴露操作 api,方便用户操作,如 mobx 的 keys, values, set
四、observable 的定义
- 从 mobx.ts 全局导出,找到 observable(src/api/observable.ts) observable API 调用方
可以看到,observable 用通过Object.assign方法 createObservable 赋值
并将 observableFactories 的 所有属性复制到 observable 下(同时也是挂在 createObservable 下)
- createObservable 劫持器
利用刚 observableFactories 挂上来的 object, array 等属性,来根据变量类型调用相应方法劫持
注意 observable 和 createObservable 是一个对象并且在相互调用
3.observable.object 调用接收三个参数
const person = observable({
name: 'aa',
get test() {
return this.showAge ? `${this.name} (age: ${this.age})` : this.name;
},
setAge(age) {
this.age = age;
}
}, { // 此为第二个参数 decorators
setAge: action
} /*, 这里传第三个 options 参数 */);
4.asObservableObject({}, options)和 asDynamicObservableObject({}, options) 处理Options
如果不传 options 返回默认的 defaultCreateObservableOptions,如果传了 options 就按照用户写的来回到第 3 步,如果 options.proxy 为 false 调用asObservableObject({}, options)
Object.defineProperty
劫持,否则调用asDynamicObservableObject({}, options)采用proxy
劫持
asObservableObject({}, options)
function addHiddenProp(object: any, propName: PropertyKey, value: any) {
defineProperty(object, propName, {
enumerable: false,
writable: true,
configurable: true,
value
})
function asObservableObject(target,options){
// ObservableObjectAdministration Type->observableobject 实例
const adm = new ObservableObjectAdministration(
target,
new Map(),
String(name),
getAnnotationFromOptions(options)
)
// addHiddenProp(target, $mobx, adm)
}
return target
}
asDynamicObservableObject({}, options)
export function asDynamicObservableObject(
target: any,
options?: CreateObservableOptions
): IIsObservableObject {
assertProxies()
target = asObservableObject(target, options)
return (target[$mobx].proxy_ ??= new Proxy(target, objectProxyTraps))
}
5.接下来 extendObservable 里面传一个已拦截的空对象A和传入对象B,进行新产物属性的初始化
所以 @observable obj ... 不会改变原来对象的
如果 properties 不为空的话(即 Object.defineProperty 劫持)则直接进行调用 extendObservableObjectWithProperties
获取到准备好的用来处理该对象的 decorator,然后传入属性装饰器需要的三个基本参数:target, key, descriptor
返回的结果就是劫持完该属性后的 resultDescriptor,再通过 Object.defineProperty 写入 target(即被 proxy 代理的 base 空对象)中
由此完成当前层的当前 key 的劫持
function startBatch() {
globalState.inBatch++
}
export function endBatch() {
if (--globalState.inBatch === 0) {
// 运行Reactions
runReactions()
// the batch is actually about to finish, all unobserving should happen here.
const list = globalState.pendingUnobservations
for (let i = 0; i < list.length; i++) {
const observable = list[i]
observable.isPendingUnobservation_ = false
if (observable.observers_.size === 0) {
if (observable.isBeingObserved_) {
// if this observable had reactive observers, trigger the hooks
observable.isBeingObserved_ = false
observable.onBUO()
}
if (observable instanceof ComputedValue) {
// computed values are automatically teared down when the last observer leaves
// this process happens recursively, this computed might be the last observabe of another, etc..
observable.suspend_()
}
}
}
globalState.pendingUnobservations = []
}
}
function extendObservable(
target: A,
properties: B,
annotations?: AnnotationsMap,
options?: CreateObservableOptions
): A & B {
// Pull descriptors first, so we don't have to deal with props added by administration ($mobx)
// Reflact.ownKeys() 返回properties 的所有属性
const descriptors = getOwnPropertyDescriptors(properties)
const adm: ObservableObjectAdministration = asObservableObject(target, options)[$mobx]
startBatch()
try {
ownKeys(descriptors).forEach(key => {
adm.extend_(
key,
descriptors[key as any],
// must pass "undefined" for { key: undefined }
!annotations ? true : key in annotations ? annotations[key] : true
)
})
} finally {
endBatch()
}
return target as any
}
-
通过上述步骤拦截器处理返回的被拦截的descriptors对象target
这个方法将object传入的第二个和第三个参数通过对象管理器添加到target上
ownKeys(descriptors).forEach(key => {
adm.extend_(
key,
descriptors[key as any],
// must pass "undefined" for { key: undefined }
!annotations ? true : key in annotations ? annotations[key] : true
)
})
五、asObservableObject 对象管理器
1.asObservableObject 劫持
通过 target(被装饰器修饰的 target,为整个对象)拿到对象的 ObservableObjectAdministration(如果对象属性值也是对象,则该属性值也会拥有 adm)
并将其挂到 target 的 $mobx 属性下,方便后面暴露 api 使用
拿到对象管理器后调用 addHiddenProp 方法,将对象当前层的当前 propertyName 劫持
adm对象管理器中封装着需要拦截的target[$mobx]方法api
export function addHiddenProp(object: any, propName: PropertyKey, value: any) {
defineProperty(object, propName, {
enumerable: false,
writable: true,
configurable: true,
value
})
}
const $mobx = Symbol("mobx administration"); // 唯一性
export function asObservableObject(
target: any,
options?: CreateObservableOptions
): IIsObservableObject {
/**xxxxxx**/
const adm = new ObservableObjectAdministration(
target,
new Map(),
String(name),
getAnnotationFromOptions(options)
)
addHiddenProp(target, $mobx, adm)
return target
}
2.ObservableObjectAdministration 管理器(后简称 adm)
export class ObservableObjectAdministration
implements IInterceptable, IListenable {
keysAtom_: IAtom
changeListeners_
interceptors_
proxy_: any
isPlainObject_: boolean
appliedAnnotations_?: object
private pendingKeys_: undefined | Map>
constructor(
public target_: any,
public values_ = new Map | ComputedValue>(),
public name_: string,
public defaultAnnotation_: Annotation = autoAnnotation
) {
this.keysAtom_ = new Atom("ObservableObject.keys")
// Optimization: we use this frequently
this.isPlainObject_ = isPlainObject(this.target_)
}
getObservablePropValue_(key: PropertyKey): any {
return this.values_.get(key)!.get()
}
setObservablePropValue_(key: PropertyKey, newValue): boolean | null {
}
get_(key: PropertyKey): any {
}
set_(key: PropertyKey, value: any, proxyTrap: boolean = false): boolean | null {
}
// Trap for "in"
has_(key: PropertyKey): boolean {
}
make_(key: PropertyKey, annotation: Annotation | boolean): void {
}
extend_(key: PropertyKey,descriptor: PropertyDescriptor,
annotation: Annotation | boolean,
proxyTrap: boolean = false
): boolean | null {
}
defineProperty_(
key: PropertyKey,
descriptor: PropertyDescriptor,
proxyTrap: boolean = false
): boolean | null {
}
defineObservableProperty_(
key: PropertyKey,
value: any,
enhancer: IEnhancer,
proxyTrap: boolean = false
): boolean | null {
}
defineComputedProperty_(
key: PropertyKey,
options: IComputedValueOptions,
proxyTrap: boolean = false
): boolean | null {
}
delete_(key: PropertyKey, proxyTrap: boolean = false): boolean | null {
}
observe_(
callback: (changes: IObjectDidChange) => void, fireImmediately?: boolean):
Lambda
{
return registerListener(this, callback)
}
intercept_(handler): Lambda {
return registerInterceptor(this, handler)
}
notifyPropertyAddition_(key: PropertyKey, value: any) {
}
ownKeys_(): PropertyKey[] {
}
keys_(): PropertyKey[] {
}
}
六、target[$mobx] 对外暴露拦截api
通过上述劫持处理后返回了一个adm对象管理器,所有在操作target时会调用adm中的方法进行拦截处理
如果通过asDynamicObservableObject 通过proxy拦截处理
function asDynamicObservableObject(
target: any,
options?: CreateObservableOptions
): IIsObservableObject {
assertProxies()
target = asObservableObject(target, options)
return (target[$mobx].proxy_ ??= new Proxy(target, objectProxyTraps))
}
objectProxyTraps 拦截handler
function getAdm(target): ObservableObjectAdministration {
return target[$mobx]
}
const objectProxyTraps: ProxyHandler = {
has(target: IIsObservableObject, name: PropertyKey): boolean {
return getAdm(target).has_(name)
},
get(target: IIsObservableObject, name: PropertyKey): any {
return getAdm(target).get_(name)
},
set(target: IIsObservableObject, name: PropertyKey, value: any): boolean {
if (!isStringish(name)) return false
return getAdm(target).set_(name, value, true) ?? true
},
deleteProperty(target: IIsObservableObject, name: PropertyKey): boolean {
if (!isStringish(name)) return false
return getAdm(target).delete_(name, true) ?? true
},
defineProperty(
target: IIsObservableObject,
name: PropertyKey,
descriptor: PropertyDescriptor
): boolean {
return getAdm(target).defineProperty_(name, descriptor) ?? true
},
ownKeys(target: IIsObservableObject): PropertyKey[] {
return getAdm(target).ownKeys_()
},
preventExtensions(target) {
die(13)
}
}