Forum Discussion

shaharbad's avatar
shaharbad
Channel Surfer
3 years ago

How to set a global variable properly?

So I'm building a channel using Brightscript, I'm facing an problem with accessing a particular variable thats located in another component, I checked online and I can't seem to understand how exactly should I do it, I tried using the global method but it doesnt work and i also tried import the script of the other file in the component xml file.

 

1 Reply

  • to expose one field from one component and to use it in another component, you have to add that field as an 'interface' and that exposes it as the equivalent of a public field in OOP programming

     

    <component name="ThisComponent" extends="ThisNode">
      <interface>

        <field id="someName" type="boolean/string/assocArray" onChange="doThis" alwaysNotify="true" />

     

     

    then you should be able to see it in the other component

     

    thisComponent = createObject("ThisComponent")

    thisComponent.someName="giveItAValueHere"

     

     

    there is also a m.global object which you can add to, but these should be genuine global variables across the app.  

     

    https://developer.roku.com/en-gb/docs/references/brightscript/interfaces/ifsgscreen.md

    sub showChannelSGScreen()
      print "in showChannelSGScreen"
      screen = CreateObject("roSGScreen")
      m.port = CreateObject("roMessagePort")
      screen.setMessagePort(m.port)
      m.global = screen.getGlobalNode()
      m.global.id = "GlobalNode"
      m.global.addFields( {red: &hff0000ff, green: &h00ff00ff, blue: &h0000ffff} )
      scene = screen.CreateScene("TrivialScene")
      screen.show()
      scene.setFocus(true)
    
      child = createObject("RoSGNode","ContentNode")
      child.contentkey = "test_string"
      print "child: '"; child.contentkey; "'"
    
      while(true)
        msg = wait(0, m.port)
        msgType = type(msg)
        if msgType = "roSGScreenEvent"
          if msg.isScreenClosed() then return
        end if
      end while
    
    end sub
     
    which can be obtained in the app as m.global.red