The importance of the clone() function/method when creating a custom Event class

0 Flares Twitter 0 Facebook 0 Google+ 0 Email -- Filament.io 0 Flares ×

I know, this is not a big thing but it can save a lot of “after-work” when you just know that it can be really useful and save you a lot of time.

I say “after-work” because I understood its importance after I thought I had finished a Loaders management class. I had to rewrite all the event parts.

So what is it ?

Just a method that clones the custom event instance with all the custom properties associated to it.

Why is it so important ?

Well, the clone() method is not necessary in all situations but it gets its importance when you need to redispatch an event for which you don’t know the type (let’s say for an event centralizer management class that doesn’t know the types of all the events it has to manage and redispatch)

When the dispatchEvent method is called, it clones the event object if it is being redispatched. By default, the clone method copies the properties of the Event object. If left like this, the custom properties associated to your custom event won’t get copied.

How to do it ?

Simply override the clone method and return a newly created instance of your custom event class with its custom properties passed to it.

See example below.

[sourcecode language=’as3′]
package
{
import flash.events.Event;

/**
* …
* @author Thomas John (thomas.john@open-design.be)
*/
public class CustomEvent extends Event
{
public var customProperty:String = “”;

public function CustomEvent(custom:String, type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
// call the constructor of the extended class
super(type, bubbles, cancelable);

// set the customProperty property
customProperty = custom;
}

override public function clone():Event
{
return new CustomEvent(customProperty, type, bubbles, cancelable);
}

}

}
[/sourcecode]

Important

The clone method must return an Event object.

[sourcecode language=’as3′]
override public function clone():Event
[/sourcecode]

But in the function, you return a new instance of your cutom event class.

[sourcecode language=’as3′]
return new CustomEvent(customProperty, type, bubbles, cancelable);
[/sourcecode]

In this case, the custom properties is passed in the constructor of the newly created instance. You can set it (or them) the way you want as long as it is before you return the object.

0 Flares Twitter 0 Facebook 0 Google+ 0 Email -- Filament.io 0 Flares ×

2 Comments

  1. prasanth

    Thanks for the post. I am exactly looking for this

  2. Nice

    Very good topic! Thanks a lot!

Leave a Comment

*