mirror of
https://github.com/dbeaver/cloudbeaver.git
synced 2026-10-16 06:40:05 +08:00
feat(core-blocks): CB-950 add bind to useObjectRef
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user