0 Replies Latest reply on Oct 3, 2007 11:30 PM by mgoodes

    Nifty tip:  How to get display container parent references to compile. (AS3)

    mgoodes
      Hello,

      I appreciate the help I've received in this forum and wanted to give back a little bit (am not familiar enough with AS3 yet to answer questions).

      Today I encountered a tricky problem in referencing a parent container. The class structure was something like this:

      class wrapper extends Sprite {

      function wrapper() {
      var displayChild = new displayChild();
      addChild( displayChild );
      }

      function parentFunction() {
      //Code here
      }

      }

      class displayChild {
      ....
      function childFunction() {
      parent.parentFunction();
      }

      }

      This code compiled and ran properly in standard mode. The problem was that this type of structure wouldn't compile in strict mode. It gave an error:

      1061: Call to a possibly undefined method parentFunction through a reference with static type flash.display:DisplayObjectContainer.

      The fix was to reference the parent like this:
      function childFunction() {
      var parentObj = parent;
      parentObj.parentFunction();
      }

      However after putting this fix into three or four functions I decided to make parentObj a global. Believe it or not, the following wouldn't compile:

      class displayChild {
      var parentObj = parent;
      }

      In other words, the compiler would only accept the fix if the parentObj reference was in a function.

      Why would this be? Any takers?

      It turns out that the parent object doesn't exist until the constructor has completed running. We encountered this in Flash MX when using embedded movie clips too. A movie clip or any display object (in AS3) doesn't exist until it is completely loaded. If it doesn't exist it doesn't have a parent. So the parent reference is invalid at compile time. It is only valid at runtime. When we call a function at runtime, the parent exists so we can assign it to parentObj and use it to call the parent.

      Luckily the compiler is forgiving enough to allow the statement:

      var parentObj = parent;

      even though parent is undefined. But of course the compiler has to allow this, otherwise it wouldn't allow us to assign any undefined values to a variable.

      Hope this is helpful to someone!

      Cheers,
      Mark