views:

343

answers:

2

I have 2 classes, Display holds the currently selected Component:

public class Display
{
 public static var selectedComponent:Component;
}

Component has an ID string and the selectedComponent variable is set on click:

public class Component extends MovieClip
{
    public var id:String;

 addEventListener(MouseEvent.CLICK, function() {
  Display.selectedComponent = this;
 });
}

I now want to be able to set the ID using Display.selectedComponent.id = "test";

The problem I have is a conversion error:

TypeError: Error #1034: Type Coercion failed: cannot convert global@4693041 to Component.

Removing the selectedComponent variable type so it reads public static var selectedComponent; removes the conversion error and seems to change the ID variable but it appears to only be a copy of the object.

Any suggestions?

Thanks

A: 

If you leave off the type (public static var selectedComponent;) it will be of type Object by default. Objects are not copied on assignment; they only hold references, so a copy will not be made.

Your code looks like it should work...

I know this makes no sense, but maybe casting this to a Component when you assign it might help: Display.selectedComponent = Component(this); You never know...

Cameron
+1  A: 

It looks to me that your scope is wrong when assigning "this" to selectedComponent. Where "this" within your local function definition is not pointing to the component class.

Try it like this:

var scope:Component = this;    
addEventListener(MouseEvent.CLICK, function() {
     Display.selectedComponent = scope;
});

or like this:

import flash.events.Event;
public class Component extends MovieClip
{


    public var id:String;

    public function Component() {
        addEventListener(MouseEvent.CLICK, onClick);
    }

    private function onClick(e:Event) {
        Display.selectedComponent = this;
    }
}
Les
or may be, you can do "Display.selectedComponent = Component(e.target);" Which I guess is much cleaner approach.
bhups
not that I'm disagreeing, but why would it be cleaner with e.target? (How 'expensive' is casting ?)
Les