触发器属性(PropertyTrigger)
表示一个可触发事件并通知监听器的触发器属性。 与其他 属性(Property) 类型不同,触发器不存储持久值。当调用 fire() 时它会发出事件。
字段(Fields)
addListener
注册一个在触发器触发时调用的监听器。
此函数有两种签名:
addListener(callback)—— 简单形式,只需传入回调函数。addListener(anchor, callback)—— 传入一个锚点对象和回调函数。 锚点对象会与监听器一同存储,并在回调被调用时传回。这对于防止某些你希望在监听期间保持存活的对象被垃圾回收很有用。
重要: 如果你使用局部变量获取 ViewModel 或属性
(例如 local vm = context:viewModel()),并在没有将该 ViewModel 存到别处的情况下添加监听器,函数返回后它可能会被垃圾回收。为避免这种情况,可以:
- 将 ViewModel 保存到
self上(例如self.vm = context:viewModel()) - 将 ViewModel 作为 anchor 参数传给
addListener
local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
cannon:addListener(function()
print("cannon fired!")
end)
cannon:fire()
end
end
使用 anchor 参数让 ViewModel 保持存活:
local vm = context:viewModel()
if vm then
local cannon = vm:getTrigger('cannon')
if cannon then
cannon:addListener(vm, function(anchor)
-- 'anchor' 是我们传入的 vm,由监听器保持存活
print("cannon fired!")
end)
end
end
removeListener
移除之前注册的监听器。 当不再需要监听器时,请始终移除它们以避免内存泄漏。
此函数有两种签名:
removeListener(callback)—— 传入要移除的回调函数。removeListener(anchor, callback)—— 传入 anchor 和回调函数。 anchor 参数出于与addListener的 API 对称性而接受, 但仅使用回调函数进行匹配。
function init(self: MyNode, context: Context): boolean
local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
self.cannon = cannon
self.onCannonFired = onCannonFired
cannon:addListener(onCannonFired)
end
end
return true
end
function removeCannonListener(self: MyNode)
if self.cannon then
self.cannon:removeListener(self.onCannonFired)
end
end
方法(Methods)
fire
fire() -> ()
触发该触发器并通知所有已注册的监听器。
local vmi = context:viewModel()
if vmi then
local cannon = vmi:getTrigger('cannon')
if cannon then
cannon:addListener(function()
print("cannon fired!")
end)
cannon:fire()
end
end