diff --git a/webapp/packages/core-blocks/src/useObjectRef.ts b/webapp/packages/core-blocks/src/useObjectRef.ts index 6bdf32a23a..b58cae38e8 100644 --- a/webapp/packages/core-blocks/src/useObjectRef.ts +++ b/webapp/packages/core-blocks/src/useObjectRef.ts @@ -9,19 +9,47 @@ import { AnnotationsMap, observable } from 'mobx'; import { useState } from 'react'; -export function useObjectRef(init: T, update?: Partial, observed?: boolean | AnnotationsMap): T { +export function useObjectRef( + init: T, + update?: Partial, + observed?: boolean | AnnotationsMap, + bind?: Array +): 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(object: T, keys: Array): void { + for (const key of keys) { + const value = object[key]; + + if (typeof value === 'function') { + object[key] = value.bind(object); + } + } +}