Using the canExecute Command Hook
This article will guide you through how to prevent a custom command from executing through the canExecute
hook.
Prerequisites
- Download and setup the Geocortex Web SDK.
- Check out the deployment instructions to learn more about deploying custom code to a Geocortex Web App.
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.
- Layout
- App Config
- Component
- Component Model
- Component Index
- Registration
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>
canExecute
Status
Add a Button to Toggle the Next, let's add a button to the custom component that will toggle the canExecute
status of the custom.command-with-can-execute
command.
- Component
- Component Model
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;
canExecute
Function
Implement the 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.
- Component Model
- UI - Command Disabled
- UI - Command Enabled
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.