// 普通业务对象显式实现 Presentable 后,ui.present 可调用其 present(window) 生成视觉对象。 // 生成的视图保存 source 指向业务模型,绑定和按钮继续使用原对象,展示不是业务数据副本。 // name/color 是业务字段,零参读取方法提供只读绑定,update 提供事件修改。 class Product { name: String color: String // 返回名称并记录实际属性读取,后续 name 修改会使文本绑定重算。 function label(self: Product): String { return self.name } // 只读返回颜色,绑定到新建色块的 color。 function shade(self: Product): String { return self.color } // 点击更新原业务对象,现有绑定会同步文字和矩形,不重新调用整个 present 构造树。 function update(self: Product, event: Event): Unit { // 由 present 中 button.on 注册的绑定方法调用,self 仍是顶层 product,不是 result 容器或 title。 self.name = "原业务对象已更新" self.color = "#237A45" } // 在指定 Window 上下文创建文字、色块和按钮,连接原 self 的方法后返回组合根。 function present(self: Product, window: Window): Block { // ui.present 验证显式能力后调用本方法,window 是本次展示上下文;每次调用都会新建下面这些视觉对象。 title = TextBlock(self.name) swatch = RectBlock(180,48,8,self.color) // 绑定令牌本身不承载另一份业务状态,绑定计算仍调用同一 Product。 titleBinding = title.bind("text",self.label) colorBinding = swatch.bind("color",self.shade) // title/swatch 的初值只是构造输入,后续 getter 绑定读取原 Product,使事件写入能继续传播。 button = Button("调用业务对象方法") connection = button.on("click",self.update) // result 保留三个视觉孩子,返回该根给调用方;这里尚未通过 Page.render 建立出现树。 result = Column(24,16,title,swatch,button) // 保留原始业务身份,便于代码从展示根回到来源;contextWindow 仅记录创建时的窗口编号。 result.source = self result.contextWindow = window.id() return result } } // 显式声明能力并验证方法契约;只有同名 present 不会自动成为 Presentable。 ui.implement(Product,Presentable) // 能力注册针对 Product 类型,实际业务字段在这个唯一实例上初始化;label/shade 将读取此实例。 product = Product("普通对象的显式展示能力", "#526AC7") // 先获得视觉根,再由 ui.open 把它挂载到页面;最后设置 Page 标题。 view = ui.present(product) // ui.open 接收上面已经生成的 Block,不会再次把 product 交给 present 重新生成另一棵视觉树。 page = ui.open(view) page.title = "Presentable"