feat(core-blocks): CB-950 add bind to useObjectRef

This commit is contained in:
Wroud
2021-04-19 19:26:43 +03:00
parent 21331096a2
commit 76aa3aa82f
@@ -9,19 +9,47 @@
import { AnnotationsMap, observable } from 'mobx';
import { useState } from 'react';
export function useObjectRef<T>(init: T, update?: Partial<T>, observed?: boolean | AnnotationsMap<T, never>): T {
export function useObjectRef<T>(
init: T,
update?: Partial<T>,
observed?: boolean | AnnotationsMap<T, never>,
bind?: Array<keyof T>
): T {
const [ref] = useState(() => {
if (observed) {
return observable.object(init, typeof observed === 'object' ? observed : undefined, { deep: false });
}
if (bind) {
bindFunctions(init, bind);
}
return init;
});
if (update) {
Object.assign(ref, update);
if (bind) {
bind = bind.filter(key => key in update);
}
} else {
Object.assign(ref, init);
}
if (bind && bind.length > 0) {
bindFunctions(init, bind);
}
return ref;
}
function bindFunctions<T>(object: T, keys: Array<keyof T>): void {
for (const key of keys) {
const value = object[key];
if (typeof value === 'function') {
object[key] = value.bind(object);
}
}
}