Files
mvvm--learn/demo/mvvm/model.py
2026-05-18 11:33:59 +08:00

46 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Model 层。
Model 负责保存业务数据。这个 demo 只有一个字符串模型 StringModel
它保存一条日志文本;当日志文本被修改时,会向事件通道发布通知。
"""
from mvvm.framework import fw_proxy, BaseModel
class StringModel(BaseModel):
"""字符串数据模型:保存一个字符串,并在值改变时发布事件。"""
def __init__(self, topic: str, value: str):
# topic 用于告诉框架:这个 Model 的变化应该发布到哪个主题。
super().__init__(topic)
# 真正保存字符串值的私有变量。
self._string = value
@property
def value(self):
"""读取当前字符串值。"""
return self._string
@value.setter
def value(self, value: str):
"""
修改字符串值。
这是 MVVM 自动刷新的关键位置:只要业务代码给 model.value 赋值,
Model 就会发布事件View 会在订阅到事件后自动刷新。
"""
self._string = value
fw_proxy.channel.publish(self._topic, value)
def signal_proxy(self, value: str):
"""
接收 View 反向传来的值。
在双向绑定场景中,如果 View 发布了自己的变化,框架会调用这里,
从而把 View 的新值同步回 Model。
"""
super().signal_proxy()
self._string = value