属性(Property)
表示一个可变属性(mutable property),可存储值并支持变更监听。
字段(Fields)
value
当前属性值(current value),支持读写。
local health = vm:getNumber("health")
if health then
print(health.value) -- read
health.value = 100 -- write
end
addListener
注册监听器,在属性值变化时调用。
此函数有两种签名:
addListener(callback)—— 简单形式,只需传入回调函数。addListener(anchor, callback)—— 传入一个锚点对象(anchor)和回调函数。 锚点对象会与监听器一同存储,并在回调被调用时传回。这样可以防止某些你希望在监听期间保持存活的对象被垃圾回收。
重要: 如果你是通过局部变量获取 ViewModel 或属性
(例如 local vm = context:viewModel()),并在没有将该 ViewModel 存到别处的情况下添加监听器,那么函数返回后它可能会被垃圾回收。为避免这种情况,可以:
- 将 ViewModel 保存到
self上(例如self.vm = context:viewModel()) - 将 ViewModel 作为 anchor 参数传给
addListener
local health = vm:getNumber("health")
if health then
local function onHealthChanged(prop)
print("New health:", prop.value)
end
health:addListener(onHealthChanged)
health.value = 50 -- Triggers listener
end
使用 anchor 参数让 ViewModel 保持存活:
local vm = context:viewModel()
local health = vm:getNumber("health")
if health then
health:addListener(vm, function(anchor)
-- 'anchor' is the vm we passed, kept alive by the listener
print("Health changed!")
end)
end
removeListener
移除之前注册的监听器。
此函数有两种签名:
removeListener(callback)—— 传入要移除的回调函数。removeListener(anchor, callback)—— 传入 anchor 和回调函数。 出于与addListenerAPI 对称性的考虑,这里接受 anchor 参数,但真正用于匹配的只有回调函数。
local health = vm:getNumber("health")
if health then
local function onHealthChanged(prop)
print("New health:", prop.value)
health:removeListener(onHealthChanged)
end
health:addListener(onHealthChanged)
health.value = 50 -- Triggers listener
end