Yida JS-API
This document mainly introduces APIs that can be directly called in the JS panel or variable binding modal of the Yida platform and their usage methods. Each API will be accompanied by an example to demonstrate the specific usage methods. In the examples, we will wrap them in the following function structure to simulate the real usage scenario of the action panel (the wrapped function names can be freely defined by users in real environments).
export function someFunctionName() {
...
}
Getting Started
The following APIs require you to have a certain foundation of JavaScript knowledge, understanding common data types, variable and function declarations and usage, while knowing and being able to navigate around some common JavaScript pitfalls.
Taking the commonly used this.state, this.setState, this.$() in the following APIs as examples, when this appears in the outermost layer of an event function, this will point to the correct execution context, thereby being able to properly read data sources, set data sources, and access other form data:
export function setSomeValue() {
const status = this.state.status;
const newStatus = status + 1;
this.setState({ status: newStatus });
this.$('numberField_xxx').setValue(newStatus);
}
However, if this appears in nested functions, you need to pay attention to whether the this reference is correct:
export function setSomeValue(value) {
// Here we save a reference to this
const that = this;
this.dataSourceMap.xxx.load(function (ret) {
// Error !!! function creates a new context environment
// Here this has changed and cannot read data sources or get other fields
this.$('numberField_xxx').setValue(ret);
// Alternative solution, use the externally saved correct reference instead
that.$('numberField_xxx').setValue(ret);
});
// Or use arrow functions to avoid this value changing
this.dataSourceMap.xxx.load((ret) => {
// Arrow functions do not create a new context, this will not be changed
this.$('numberField_xxx').setValue(ret);
});
}
Recommended JavaScript beginner guides:
- JavaScript Introduction on MDN
- JavaScript Reference - Expressions and Operators - this
- JavaScript Garden
- Stack Overflow
Global Variable API
Yida's design pattern mainly refers to React's approach, so we provide global variables for page-level state management and provide corresponding APIs to trigger page re-rendering (for specific usage, refer to Global Variables Document).
this.state.xxx
Get the value of global variables (consistent with React's API).
xxx is generally the variable name of the page data source.
Example:
export function getState() {
// Get the value of the page global variable and print it via console
const status = this.state.status;
console.log( `status: ${status}` )
}
this.setState()
Set the value of global variables and trigger page re-rendering (basically consistent with React's API).
Note: Prohibited to use this.state.a = b method to modify variable values, future upgrades cannot guarantee compatibility, related code will not run properly.
Example:
export function setStateValue() {
// Set the value of page global variables and trigger page re-rendering
this.setState({
status: 'loading',
text: 'Loading…'
});
}
Remote Data API
Yida supports configuring remote data sources and provides APIs to trigger remote data source calls via JS (for specific usage, refer to Remote API Document).
this.dataSourceMap.xxx.load()
Manually call the specified remote API, where xxx is the data source name set in the data source panel. It also supports passing request parameters. The request parameters passed to the API call will be merged with the request parameters in the data source configuration and sent in the request. The load method returns a Promise.
Example:
export function fetchData() {
// Request the configured getDataList remote API in the data source, and pass in pageSize and page parameters. If the request succeeds, print the result in the console. If the request fails, pop up an alert.
this.dataSourceMap.getDataList.load({
pageSize: 10,
page: this.state.currentPage
}).then((res) => {
if (res) {
console.log('fetchData', res);
}
}).catch((err) => {
this.utils.toast({
type: 'error',
title: 'Request failed!'
});
});
}
this.reloadDataSource()
Re-request all remote APIs with auto-load set to true. This method also returns a Promise.
Example:
export function reload() {
// Re-request all initial requests, pop up an alert after request succeeds
this.reloadDataSource().then(res => {
this.utils.toast({
type: 'success',
title: 'Refresh successful!'
});
});
}
JS Calling API
Yida provides an action panel for JS code writing. Functions in the action panel can be used not only for variable binding and action binding but also support mutual function calls.
this.methodName()
We provide related calling methods for js functions in the action panel. Users can use this.xxx() to call other functions in the action panel, where xxx is the name of the other function.
Example:
export function hello(params) {
this.utils.toast({
title: `hello ${params}` ,
type: 'success'
})
}
export function onClickInvoke(){
const value = this.$('textField_k1u12o6l').getValue()
// Call other functions in the action panel
this.hello(value)
}
Utility Class Related API
Yida provides many built-in utility functions to help users better implement some common functions.
this.utils.dialog()
Pop up a dialog, the effect is shown in the figure below, users need to manually close:

Yida's underlying implementation uses fusion components. You can configure all Dialog component properties Documentation address, the following lists common properties:
| Parameter | Property | Default Value | Description |
|---|---|---|---|
| type | 'alert', 'confirm', 'show' | 'alert' | - |
| title | (String) | - | - |
| content | (String|ReactNode) | - | Can also pass HTML/JSX to implement complex layouts |
| hasMask | (Boolean) | true | Whether there is a mask |
| footer | (Boolean) | true | Whether there are bottom operation buttons |
| footerAlign | 'left', 'center', 'right' | 'right' | Bottom operation alignment direction |
| footerActions | ['cancel', 'ok'], ['ok', 'cancel'], ['ok'], ['cancel'] | - | Bottom operation type and order |
| onOk | (Func) | - | Callback function for clicking OK |
| onCancel | (Func) | - | Callback function for clicking Cancel |
Example:
export function popDialog(){
this.utils.dialog({
type: 'confirm',
title: 'title',
content: 'content', // If line break is needed, you can pass HTML/JSX to implement
onOk: () => { },
onCancel: () => { },
});
}
// Supports manual closing of dialog
export function closeDialog() {
// Accept dialog return value, which is an object
const dialog = this.utils.dialog({});
// Call the object's hide method to close the dialog at the appropriate time
dialog.hide();
}
this.utils.formatter()
Commonly used formatter functions for formatting dates, amounts, phone numbers, etc.
Example:
export function format() {
// Format date, output value: 2022-01-29
const formatDate = this.utils.formatter('date', new Date(), 'YYYY-MM-DD');
// Format date, output value: 2022/01/29
const formatDate = this.utils.formatter('date', new Date(), 'YYYY/MM/DD');
// Format date, output value: 2022-01-29 13:01:02
const formatDate2 = this.utils.formatter('date', new Date(), 'YYYY-MM-DD HH:mm:ss');
// Format money, output value: 10, 000.99
const formatMoney = this.utils.formatter('money', '10000.99', ', ');
// Format phone, output value: +86 1565 2988 282
const formatPhoneNumber = this.utils.formatter('cnmobile', '+8615652988282');
// Format bank card number, output value: 1565 2988 2821 2233
const formatCardNumber = this.utils.formatter('card', '1565298828212233');
}
this.utils.getDateTimeRange(when, type)
Get current or specified date's start and end time range timestamps.
Both when and type are optional, by default returns the start and end time range for the current day. You can specify date and time range type.
| Parameter | Property | Default Value | Description |
|---|---|---|---|
| when | Supports timestamp, Date type | Current time new Date() | Specified date |
| type | 'year', 'month', 'week', 'day', 'date', 'hour', 'minute', 'second' | 'day' | Type of time range to get |
Example:
export function search() {
const [dayStart, dayEnd] = this.utils.getDateTimeRange();
console.log(`dayStart: ${dayStart}, dayEnd: ${dayEnd}`);
// Outputs the start and end timestamps for the current day
const [monthStart, monthEnd] = this.utils.getDateTimeRange(new Date(), 'month');
console.log(`monthStart: ${monthStart}, dayEnd: ${monthEnd}`);
// Outputs the start and end timestamps for the current month
}
this.utils.getLocale()
Get the current page's language environment.
Example:
export function locale() {
const locale = this.utils.getLocale();
console.log(`locale: ${locale}`);
// Output: locale: zh_CN
}
this.utils.getLoginUserId()
Get the logged-in user ID.
Example:
export function getUserInfo() {
const userId = this.utils.getLoginUserId();
console.log(`userId: ${userId}`);
// Output: userId: 43314767738888
}
this.utils.getLoginUserName()
Get the logged-in user name.
Example:
export function getUserInfo() {
const userName = this.utils.getLoginUserName();
console.log(`userName: ${userName}`);
// Output: userName: 韩火火
}
this.utils.isMobile()
Determine if the current access environment is on a mobile device.
Example:
export function someFunctionName() {
console.log('isMobile', this.utils.isMobile());
}
this.utils.isSubmissionPage()
Determine if the current page is a data submission page.
Example:
export function someFunctionName() {
console.log('isSubmissionPage', this.utils.isSubmissionPage());
}
this.utils.isViewPage()
Determine if the current page is a data viewing page.
Example:
export function someFunctionName() {
console.log('isViewPage', this.utils.isViewPage());
}
this.utils.loadScript()
Dynamically load remote scripts.
Example:
export function didMount() {
this.utils.loadScript('https://g.alicdn.com/code/lib/qrcodejs/1.0.0/qrcode.min.js').then(() => {
var qrcode = new QRCode(document.getElementById('qrcode'), {
text: "http://jindo.dev.naver.com/collie",
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
});
}
this.utils.openPage()
Open a new page.
If in a DingTalk environment, it will use DingTalk API to open a new page, which will provide a better experience.
Example:
export function someFunctionName() {
this.utils.openPage('/workbench');
}
this.utils.previewImage()
Image preview. With this API we can implement a simple image preview effect as shown below:

Example:
export function previewImg() {
this.utils.previewImage({ current: 'https://img.alicdn.com/tfs/TB1JUnZ2GL7gK0jSZFBXXXZZpXa-260-192.png_.webp' });
}
this.utils.toast()
Information reminder, which will be more lightweight than Dialog. After popping up, it will automatically disappear after a period of time. The effect is shown in the figure below:

Parameter configuration:
| Parameter | Property | Default Value | Description |
|---|---|---|---|
| type | 'success', 'warning', 'error', 'notice', 'help', 'loading' | 'notice' | - |
| title | (String) | - | - |
| size | 'medium', 'large' | 'medium' | - |
| duration | (Number) | - | Invalid when type is loding |
Example:
export function popToast(){
this.utils.toast({
title: 'success',
type: 'success',
size: 'large',
})
}
// Supports manual call to close method
export function showLoadingToast() {
// Get return value, which is a close method
const close = this.utils.toast({
title: 'Loading',
type: 'loading',
size: 'large',
});
// Call close method at appropriate time
setTimeout(close, 3000);
}
Routing Related API
Yida provides APIs for getting routing information and page navigation. The underlying implementation primarily uses react-router, so the navigation APIs are basically consistent with react-router APIs. Additionally, Yida provides some routing-related extension APIs.
this.utils.router.push()
Page navigation that pushes navigation records to the routing stack. Navigation can be undone using the browser's back button. The parameters for push are described as follows:
function push(path: string, params?: object, blank?: boolean, isUrl?: boolean, type?: string) => void;
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| path | string | Yes | The navigation address, can be a complete URL, URL fragment, or a string composed of pageID. If there is a slug, priority is given to using slug (page alias, Yida has not yet opened configuration) for navigation. When the isUrl parameter is true, it will be parsed as a URL. Otherwise, it will be parsed as pageId form to achieve internal page-to-page navigation. |
| params | object | No | Query parameters for the navigation address {q: 'a', r: 'b'} equivalent to ?q=a&r=b |
| blank | boolean | No | Whether to open a new page, default value is false |
| isUrl | boolean | No | Whether it is a url address, default value is false |
| type | string | No | Optional values are push or replace, using push or replace to navigate |
Example:
export function pushUrl() {
// Navigate to page, and inject fromSource parameter. The final destination will be: https://www.aliwork.com?formSource=customPage
this.utils.router.push('https://www.aliwork.com', {fromSource: 'customPage'});
}
this.utils.router.replace()
Page replacement. The difference from router.push is that this API will replace the current page instead of navigating to the next page, so it cannot be undone using the browser's back button. Equivalent to:
this.utils.router.push(path, params, false, false, 'replace');
Example:
export function replaceUrl() {
// Navigate to page, and inject fromSource parameter
this.utils.router.replace('https://www.aliwork.com', {fromSource: 'customPage'});
}
this.utils.router.getQuery()
Get page URL parameters. If a key parameter is passed, it returns the defined parameter value; otherwise, it returns all parameters of the URL. The parameters for getQuery are described as follows:
function getQuery(key?: string, queryStr?: string) => Record<string, string> | string | undefined;
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| key | string | No | Pass key to return corresponding value, otherwise return entire object |
| queryStr | string | No | Default value: location.search + location.hash, hash overrides search; supports custom string parsing, format is '?a=1&b=2' |
Example:
export function getQuery() {
// Get fromSource parameter from URL
const fromSource = this.utils.router.getQuery('fromSource');
console.log(`fromSource: ${fromSource}`);
}
this.utils.router.stringifyQuery()
Serialize URL parameters, converting objects to URL parameter form.
Example:
export function stringifyQuery() {
// Serialize object to URL parameter form and print via console
const params = {
name: 'yida',
gender: 'm'
};
const urlStr = this.utils.router.stringifyQuery(params);
console.log(`urlParams: ${urlStr}`);
// Output result is: urlParams: name=yida&gender='m'
}
Component General API
Before explaining component-related APIs, a few concepts need to be introduced in advance:
- Component unique identifier (fieldId) - Yida will set a unique identifier for each component to identify component instances. Component unique identifiers can be viewed through the component property panel;
- Component attribute (prop) - In Yida, each component can implement different functions by setting component attributes (similar to React's props). We can view the corresponding attribute names of configuration items by hovering over the component property panel;

Component general API can be used for all components provided by Yida, mainly for reading or setting component attributes.
this.$(fieldId).get(prop)
Find the component by fieldId and get the component's attribute value. fieldId is the component identifier, prop is the component's attribute name.
Note: Prohibited to use this.$(fieldId).xxx method to read attribute values. Future upgrades cannot guarantee compatibility, and related code will not run properly.
Example:
export function getAttribute(){
// Get the content attribute of the text component and print in console
const content = this.$('text_kyz78exo').get('content')
console.log(`text content: ${content}`);
}
this.$(fieldId).set(prop, value)
Find the component by fieldId and set the component's attribute value. fieldId is the component identifier, prop is the component attribute name, value is the attribute value to be set.
Note: Prohibited to use this.$(fieldId).xxx = xxx method to set attribute values. Future upgrades cannot guarantee compatibility, and related code will not run properly.
Example:
export function setAttribute(){
// Set the maximum lines (maxLine) attribute of the text component
this.$('text_kyz78exo').set('maxLine', 5);
}
Form Component API
Form components are the most important category of components in the Yida platform. We usually use form components to collect data, such as: input boxes, radio buttons, checkboxes, dropdown selections, etc. This section will mainly introduce form component-related APIs:
this.$(fieldId)
Get component instance, fieldId is the component unique identifier. Before calling component APIs, we usually need to get the component instance first through this.$(fieldId) and then call the API.
Note: Prohibited to use this.$(fieldId).xxx method to get APIs and attributes not specified in the document. APIs and attributes not specified in the document are private internal implementations. Future upgrades cannot guarantee compatibility, and related code will not run properly.
this.$(fieldId).getValue()
Get the input value of the specified form component.
Example:
export function getValue(){
// Get user input value of the input box component and print in console
const value = this.$('textField_kyz78exp').getValue();
console.log(`input value: ${value}`);
}
this.$(fieldId).setValue()
Set the input value of the specified form component. The parameters for setValue are described as follows:
interface IOptions {
doNotValidate: boolean; // Whether to prevent automatic validation, default is false
formatted: boolean; // Whether already formatted, default is false
triggerChange: boolean; // Whether to trigger component value change event, default is true
};
/**
* @param {any} value The form value to be set
* @param {IOptions} [options] Configuration options, optional
*/
function setValue(value: any, options?: IOptions) => void;
Example:
export function setValue(){
// Set the value of the input box component to 'hello world'
this.$('textField_kyz78exp').setValue('hello world');
}
this.$(fieldId).reset()
Reset the input value of the specified form component. The parameters for reset are described as follows:
/**
* @param {boolean} toDefault Whether to reset to the form component's default value, default is true
*/
function reset(toDefault?: boolean) => void;
Example:
export function reset() {
// Reset the value of the input box component
this.$('textField_kyz78exp').reset();
}
this.$(fieldId).getBehavior()
Get the current state of the specified form component. Form component states have the following possible values:
- NORMAL - Normal state, i.e., input state;
- READONLY - Read-only state;
- DISABLED - Disabled state;
- HIDDEN - Hidden state;
Example:
export function getBehavior() {
// Get the state of the input box component and print it
const behavior = this.$('textField_kyz78exp').getBehavior();
console.log(`text behavior: ${behavior}`);
}
this.$(fieldId).setBehavior()
Set the state of the specified form component. States that can be set can be referenced in the getBehavior section description.
Example:
export function setBehavior() {
// Set the state of the input box component to disabled (DISABLED) state
this.$('textField_kyz78exp').setBehavior('DISABLED');
}
this.$(fieldId).resetBehavior()
Reset the state of the specified form component.
Example:
export function resetBehavior() {
// Reset the state of the input box component
this.$('textField_kyz78exp').resetBehavior();
}
this.$(fieldId).validate()
Execute validation once for the specified form component. The parameters for validate are described as follows:
/**
* @param {Array|null} errors Error information, null if no errors
* @param {Object} values Form component values
*/
function ValidateCallback(errors: string[] | null, values: object | null) => void
/**
* @param {Function} callback Validation callback method, optional
*/
function validate(callback?: ValidateCallback) => void;
Example:
export function validate() {
// Execute validation of the input box component. If validation fails, print errors and values in console
this.$('textField_kyz78exp').validate((errors, values) => {
console.log(JSON.stringify({errors, values}, null, 2));
});
}
When a textbox's validation rule is for phone numbers, if validation fails, it will print the following structure:
{
"errors": {
"textField_kyz78exp": {
"errors": [
"Input field is not in a valid mobile phone number format"
]
}
},
"values": {
"textField_kyz78exp": "33"
}
}
this.$(fieldId).disableValid()
Turn off form component validation.
Example:
export function disableValid() {
this.$('textField_kyz78exp').disableValid();
}
this.$(fieldId).enableValid()
Enable form component validation. The parameters for enableValid are described as follows:
/**
* @param {boolean} doValidate Whether to execute validation immediately, optional, default is false
*/
function enableValid(doValidate?: boolean) => void;
Example:
export function enableValid() {
// Enable input component validation and execute immediately
this.$('textField_kyz78exp').enableValid(true);
}
this.$(fieldId).setValidation()
Set form component validation rules. The parameters for setValidation are described as follows:
interface IRule {
type: string; // Validation type
param: any; // Parameters corresponding to validation type
message: string; // Error message
}
/**
* @param {IRule[]} rules Validation rules, required
* @param {boolean} [doValidate] Whether to execute validation immediately, optional, default is false
*/
function setValidation(rules: IRule[], doValidate?: boolean) => void;
Supported validation types in Yida are shown below:
| Supported validation rules | Attribute |
|---|---|
| Required | {"type": "required"} |
| Minimum length | {"type": "minLength", "param": "23" } |
| Maximum length | {"type": "maxLength", "param": "23" } |
{"type": "email"} | |
| Mobile | {"type": "mobile"} |
| URL | {"type": "url"} |
| Minimum value | {"type": "minValue", "param": "3"} |
| Maximum value | {"type": "maxValue", "param": "3"} |
| Custom function | {"type": "customValidate", "param": (value, rule) => { return ture; }} |
Example:
export function setValidation() {
// Set validation rules for the input component, required, maximum length of 10 and
this.$('textField_kyz78exp').setValidation([{
type: 'required'
}, {
type: 'maxLength',
param: '10'
}, {
type: 'customValidate',
param: (value, rule) => {
if(/^\d*$/.test(value)) {
return true;
}
return rule.message;
},
message: 'Can only input numbers'
}]);
}
this.$(fieldId).resetValidation()
Reset form component validation rules, i.e., used after setValidation to restore previous validation rules. The parameters for resetValidation are as follows:
/**
* @param {boolean} [doValidate] Whether to execute validation immediately, optional, default is false
*/
function resetValidation(doValidate?: boolean) => void;
Example:
export function resetValiation() {
// Reset validation rules of input box component and validate immediately
this.$('textField_kyz78exp').resetValidation(true);
}
Dialog Component API
Yida provides a dialog component for displaying dialog-form content, while also providing some APIs to operate dialog behaviors.
this.$(fieldId).show()
Display specified dialog. This API provides a callback function that can be called after the dialog is shown.
Example:
export function openDialog() {
this.$('dialog_kyz78exr').show(() => {
console.log('Dialog is open');
});
}
this.$(fieldId).hide()
Close specified dialog.
Example:
export function closeDialog() {
this.$('dialog_kyz78exr').hide();
}