`

A method called 'delete' in Flex and AS3

02 Jul 2009

Archive Notice: This post is an archive post from my older blog. Comments are disabled and the information contained in it may no longer be accurate.

You are in for a headache if you have try to call a method or create a member variable with the name of a reserved word in Actionscript. It can lead to such fun situations as having variables called: insert; update; deleteSomething. Because calling the third variable delete may be logical but it is a reserved word so that is out of the question. It gets hairier when you don’t necessarily have control over the object format (such is often the case with remote calls). I ran into this today when trying to call the node_delete (or node.delete) method in Drupal via Services and AMFPHP. This is frustrating so I'm going to show two situations where you could run into this problem and how I fixed them.

Situation #1: A variable named "new" in a dynamic class

You are creating a dynamic object and you need to use a reserved word as a member variable name but you can't.

var x:Object = new Object;
x.new = "this doesn't work";
x['new'] = "this works";

The first method is a nice way to get 1084: Syntax error: expecting identifier before new when you try to compile. Remove that line and use just the second one and you are all set. It is OK to mix and match access methods, as long as you never use dot notation for reserved words.

Situation #2: A RPC method named delete

You are making a remote call via the RemoteObject class (such as I was doing with Drupal) and you need to call a method named delete (or new for that matter). You naturally try this:

var ro:RemoteObject = new RemoteObject;
ro.endpoint = "http://www.example.com/amfphp";
ro.delete( 1234 );

You will be promptly greeted by the now familiar 1084 error when you try to compile and using a different notation won’t work. I’ll break the solution into multiple parts although it could just as easily be chained together:

var op:AbstractOperation = ro.getOperation('delete');
op.send( 12345 );

Incidentally the result of the send method is a AsyncToken object (the same object that ro.delete() would return if delete were not reserved) which can then be used to add responders.

There you have it. Two quick and easy ways to get around methods and properties with reserved words for names.