Microsoft MakeCode

How to add functions in a class and set the object automatically?

Hi,
Posting it here as unsure if its more relevant here.
I want to have all my functions in a class for each main block. Right now what I do is,

namespace ABC{
//% block=“create lcd settings”
//% blockSetVariable=“ABCObjSettings”
//% weight=110
export function createABCObjSettings(): ABCObjSettings{
return new ABCObjSettings();
}
export class ABC{



//% block="$this example $variablePassed
//% blockId=Example
//% blockNamespace=ABC
//% this.shadow=variables_get
//% this.defl=“ABCObjSettings”
//% weight=90
exampleExposedFunction(variablePassed : number) {

sum=this.variablePassed

}

}

}

In the blocks on the webpage, I have to first place the “set ABCObjSettings to create lcd settings”, then select my exposed function.
I have to place the “set ABCObjSettings to create lcd settings” at least once to use any exposed

Is there a way to automatically create that Object and use?

Thanks!

Any answers?

To clarify, does the user need to be able to create multiple of these objects, or is this just internal state? If they need to be able to use multiple, they’ll likely need to have a reference to it, so there will need to be a block to create one.

If it’s just internal state needed to keep track of things in your extension, though, you can just store it as a variable within a namespace, and lazily create it whenever they first case a function. For example, something like

namespace mycoolextension {
    class CoolExtensionInternalState {
        field: number;
        constructor() { }
    }

    let stateInstance: CoolExtensionInternalState;
    function init() {
        if (!stateInstance) {
            stateInstance = new CoolExtensionInternalState();
        }
    }

    //% block definition stuff here
    export function exposedFunction(variablePassed: number) {
        init();
        stateInstance.field = variablePassed;
    }
}

If you keep track of it internally, it’s just state you’re maintaining / not something you’d ever expose to the user. The init function would be called in all functions that need to reference or modify the state to lazily create anything you need.

Hi,
Thanks for the reply. I tried this but it doesn’t work if the exposed function is inside the class. I want all my functions inside the class.