自定义模型接口与 JavaScript
本示例将模型的温度公开为属性,通过事件报告温度超过阈值的时刻,并用方法封装对内部组件的操作。
创建模型
- 打开 **Custom Model(自定义模型)**面板,添加一个模型。
- 添加数据类型为
LREAL的自定义属性temperature和alarmLimit,以及类型为BOOL的overLimit。将这些名称同时设为各属性的 Name for JS Access(JS 访问名称)。 - 添加自定义事件
ThresholdExceeded,带有一个LREAL参数。将其 JS 访问名称设为ThresholdExceeded。 - 添加内部数值组件,将其 Value 属性绑定到模型的
temperature。添加内部图片组件,将其 Visible 属性绑定到overLimit。这些内部组件由模型的公开接口封装。 - 添加自定义方法
ResetAlarm。定义一个 **Set value(设置值)**动作,将模型的overLimit设为false。图片的绑定会随之更新可见状态。将该方法的 JS 访问名称设为ResetAlarm。
属性绑定和方法动作将与数值组件的交互封装在模型内。自定义组件的调用方无需知道内部组件的名称或布局。
添加模型脚本
javascript
this.property.overLimit = this.property.temperature > this.property.alarmLimit;
const subscriptionId = this.property.$subscribe('temperature', (newValue, oldValue) => {
const overLimit = newValue > this.property.alarmLimit;
this.property.overLimit = overLimit;
if (overLimit && oldValue <= this.property.alarmLimit) {
this.event.ThresholdExceeded.emit(newValue);
}
});
// The model can invoke its own custom Method when its logic calls for it:
// this.method.ResetAlarm();
// Cancel the subscription if the script no longer needs it:
// this.property.$unsubscribe(subscriptionId);将模型作为自定义组件使用,按需绑定每个实例的自定义属性,并在自定义组件上处理 ThresholdExceeded。订阅回调会收到 (newValue, oldValue),$subscribe 返回传给 $unsubscribe 的 ID。
检查公开的方法和事件
只有 JS 访问名称非空的成员才会公开。用 in 检查成员是否存在,用 Object.keys 查看接口。
javascript
console.log('ResetAlarm' in this.method); // true
console.log('ThresholdExceeded' in this.event); // true
console.log(Object.keys(this.method)); // ['ResetAlarm']
console.log(Object.keys(this.event)); // ['ThresholdExceeded']
console.log(this.method.ResetAlarm.name); // 'ResetAlarm'
console.log(this.event.ThresholdExceeded.emit.name); // 'emit'
console.log(`${this.method} / ${this.event}`); // [object Method] / [object Event]查找未知或空名称会返回 undefined。命名空间为只读,请在模型编辑器中定义接口。要动态选取事件,请先用 eventName in this.event 检查,再调用 this.event[eventName].emit(value)。
要与设备交换数据,可将自定义属性绑定到 EBX 变量或属性,脚本通过该属性操作数据。