Rob's garden / notes / note

Note

Explicit Resource Management in #JavaScript is very useful for creating semaphores/locks around code. Here's one I just wrote with #vue

There's a ref that contains the lock value, the template binds to "disabled" on the form/button below.

If a lock is established (ie it was false), it is set to true for the duration of the function. If the method is called again while it is still processing, it will be locked and exit early.

Once the processing completes, the lock is automatically released because of the "using" statement at the top!

I've also been experimenting with trying to use more web-native client-side code, hence the use of a SubmitEvent and FormData, rather than v-modelling data

The "createLock" method is quite simple too.

It returns null when the lock was not established. If it can be locked, it writes the value to true and returns an object with the special "dispose" method.

The runtime automatically calls that method when the variable that it is bound to exits its scope. This works for both, the function calling this ending and if an error was thrown.

It seems @vite doesn't support Explicit Resource Management right now, so this is all a bit anticlimactic

dark-themed JavaScript code reading:

const isWorking = ref(false);

async function submitAnnotationLayer(e: Event) { using lock = createLock(isWorking); if (!lock) return;

const data = new FormData(e.target as HTMLFormElement); console.log("create annotation", data);

await apiClient.maps.createAnnotationLayer(props.mapId, { name: data.get("name") as string, geometry: { type: "FeatureCollection", features: [] }, }); }

dark-themed JavaScript code reading:

export function createLock(ref: Ref) { if (ref.value) return null; ref.value = true; return { Symbol.dispose { ref.value = false; }, }; }