首页 > 解决方案 > 如何将匿名函数的对象传递给另一个对象?

问题描述

我正在尝试创建一组位于关联数组中的回调函数,然后将其保存到另一个场景图形对象的接口字段。

但是,当访问同一对象中的接口字段时,它表明该功能无效。

对象 1:

callbacks = {
    afterchildcreatecallback: function ()
      print "THIS IS A CALLBACK FUNCTION"
      return 1
    end function
  }

  m.contentReader = createObject("roSGNode", "ContentReader")
  m.contentReader.observeField("content", "setLists")
  m.contentReader.contenturi = "pkg:/data/contentLists/" + settingFocused.id + "Data.xml"
  m.contentReader.callbacks = callbacks
  m.contentReader.control = "RUN"

对象 2:

<component name = "ContentReader" extends = "Task" >
  <script type = "text/brightscript" uri="pkg:/components/taskRunners/contentReader.brs"></script>

  <interface>
    <field id = "contenturi" type = "uri"></field>
    <field id = "content" type = "node"></field>
    <field id = "callbacks" type = "assocarray"></field>
  </interface>

</component>

访问对象 2 中的回调字段时,我可以看到添加的对象,但其中定义的函数无效。

这是允许的吗?还是我必须通过setter方法传递函数?

标签: rokubrightscriptscenegraph

解决方案


您不能将函数存储在接口关联数组字段中。这要么是 BrightScript 的限制,要么是设计功能。如果您想使用侦听器回调模式,您仍然可以使用接口函数通过callFunc().

你的节点.xml

<component name="YourNode" extends="Node">
  <interface>
    <function name="myCallback"/>
  </interface>
</component>

你的节点.brs

sub init()
  m.contentReader = createObject("roSGNode", "ContentReader")
  m.contentReader.listener = m.top
  (...)
end sub

sub myCallback(params)
  ?"params "params
end sub

内容阅读器.xml

<component name="ContentReader" extends="Task">
  <interface>
    (...)
    <field id="listener" type="node"/>
  </interface>
</component>

内容阅读器.brs

sub onTaskDone()
  params = ...
  m.top.listener.callFunc("myCallback", params)
end sub

此外,请确保在完成后“释放”侦听器引用,您可以YourNode通过做m.contentReader.listener = invalid. 这将避免由循环引用引起的内存泄漏。


推荐阅读