Message from JavaScript discussions

April 2019

— A util then!

— 

The selector I pass could also be a parent. I normally pass one selector and based on this selector I have hardecoded selectors in the constructor

— But each selector could fail

— 

const assertExists = (
selector,
parent = document.body,
fallback
) => {
const elem = parent
.querySelector(selector);
if (!elem) {
if (fallback) {
return assertExists(fallback, parent);
}
throw new Error(
'Selector matched no elements: ' +
selector);
}
return elem;
}


constructor(params) {
const { selector1, selector2 } = params;
this.foo = assertExists(selector1);
this.bar = assertExists(selector2, this.foo);
}

Message permanent page

— What do you want to do if they fail?

— Thanks!
Depends on the elem. Some are necessary some are not. I want to be able to provide a fallback or if its a necessary elem at best delete the instance. Is it possible to delete a class instance inside of the class?

Message permanent page

— Throw during construction

— Prevents creating the class

— Oh nice. Perfect.

— What if the fallback fails?

— Also delete the instance / prevent creating one

— Edited