Using the canExecute Command Hook

This article will guide you through how to prevent a custom command from executing through the canExecute hook.

Prerequisites

Create an App with an IWTM and a Custom Component

First, let's create an app with an IWTM and a custom component that implements a simple command that displays an alert.

app/layout.xml
<?xml version="1.0" encoding="UTF-8"?>
<layout xmlns="https://geocortex.com/layout/v1" xmlns:custom="custom.abc123">
<map>
<iwtm config="iwtm-config" slot="top-left" />
<custom:custom-component margin="3" slot="top-center"/>
</map>
</layout>

Add a Button to Toggle the canExecute Status

Next, let's add a button to the custom component that will toggle the canExecute status of the custom.command-with-can-execute command.

src/components/CustomComponent.tsx
import {
LayoutElement,
LayoutElementProperties,
} from "@vertigis/web/components";
import Button from "@vertigis/web/ui/Button";
import React from "react";
import CustomModel from "./CustomModel";
const CustomComponent = (props: LayoutElementProperties<CustomModel>) => {
const { model } = props;
return (
<LayoutElement {...props}>
<Button onClick={() => model.toggleCanExecute()}>
Toggle Can Execute
</Button>
</LayoutElement>
);
};
export default CustomComponent;

Implement the canExecute Function

Finally, we need to implement the canExecute method for the custom.command-with-can-execute command. This method should be decorated with @canExecute and return a boolean indicating whether the command can execute.

tip

If the command takes an argument, the @canExecute method will also be passed that argument.

src/components/CustomModel.ts
import { ComponentModelBase, serializable } from "@vertigis/web/models";
import { command, canExecute } from "@vertigis/web/messaging";
@serializable
export default class CustomModel extends ComponentModelBase {
private _canExecuteValue: boolean = false;
@command("custom.command-with-can-execute")
protected _commandWithCanExecute(): void {
this.messages.commands.ui.alert.execute({
message: "Executed `custom.command-with-can-execute`",
});
return;
}
@canExecute("custom.command-with-can-execute")
protected _canExecuteImplementation_(): boolean {
return this._canExecuteValue;
}
toggleCanExecute(): void {
this._canExecuteValue = !this._canExecuteValue;
this.messages
.command("custom.command-with-can-execute")
.canExecuteChanged.publish();
}
}

Next Steps

Check out a live SDK sample of a command that has a canExecute hook.