29 lines
1.8 KiB
Plaintext
29 lines
1.8 KiB
Plaintext
// 字段类型契约示例:CounterText 同时有原生文本载荷和源 Number 字段。
|
|
// 绑定显示读取该字段,GUI 回调与 Console 赋值受同一契约约束。
|
|
// 不匹配的字段写入保留该字段旧值;这不表示整次回调或同一输入中较早的其他写入都会回滚。
|
|
// 增加 value:Number;构造时先传原生 text,再传源字段值。
|
|
class CounterText: TextBlock {
|
|
// value 是源字段,不是 TextBlock 的原生 text;页面把两者作为不同内容分别展示。
|
|
value: Number
|
|
// 收到 click 后把已有数值改为 10,依赖文字随之更新,不修改原生 text 内容。
|
|
function change(self: CounterText, event: Event): Unit {
|
|
// button.on("click", ...) 派发时提供 event;本例不读取事件载荷,只向受 Number 契约保护的字段写值。
|
|
self.value = 10
|
|
}
|
|
}
|
|
// 声明 target 必须是 Block,可接收 CounterText,因为它是 TextBlock 的子类。
|
|
class Model {
|
|
// 这里用父类型约束对象身份;不复制 counter,也不将它退化为只有 Block 字段的新对象。
|
|
target: Block
|
|
}
|
|
// 构造唯一受检对象,Model、事件回调和 textOf 均引用它。
|
|
counter = CounterText("共享的原生子类对象", 9)
|
|
model = Model(counter)
|
|
// model 仅演示构造时接受子类型;下面的回调和绑定直接引用 counter,不经过 model.target。
|
|
button = Button("把 Number 字段改成 10")
|
|
connection = button.on("click", counter.change)
|
|
// 保留 connection 供后续管理订阅;回调的接收者已经绑定为 counter,页面只负责把它与数值绑定挂载出来。
|
|
page = Page()
|
|
page.title = "字段类型契约"
|
|
page.render(Column(24, 16, counter, ui.textOf(counter, "value"), button, TextBlock("GUI 和源码写入同一个受检查的字段")))
|