View all posts filed under 'Basic Code'

What a difference a word makes – especially when converting a String to XML in ActionScript!

Friday, 13. February 2009 18:17

OK – this isn’t a biggie but maybe it’ll help some other poor soul.  Basically I’m loading XML into my swf.  It’s in ActionScript 2………… lots of reasons why, but no matter.  I’ve shaken the dust off my OOP AS2 muscles and got started.

I was happily loading and parseing the XML when suddenly I was told that we wouldn’t neccessarily be getting the XML from a flat file but also from a webservice.  No probs, thought I gaily, all I need to do is point at the webservice and call the XML.  It’s formatted exactly the same – should be fine.

Nope.  Basically when I’d been loading the static XML I was casting the type to XML like this

var loadedXML:XML = XML(loadedFile);

This works fine for a flat file.  However if you are loading from a webservice it ignores the xml structure of the recieved data and treats it as a single string.  To fix this all you need is to amend the above to : -

var loadedXML:XML = new XML(loadedFile);

Category:Basic Code | Comment (0) | Author: admin

Flex Dynamic Data Binding 101 – Part Four, Finishing the Contact App

Monday, 14. January 2008 8:23

So we’ve created our basic application in part three. You can see it here.

Adding and deleting is fine, but what about editing? I don’t want to simply add people, I want to be able to change them too. We’re going to need a few more variables and another function.

<mx:Script>
	<![CDATA[
		import mx.collections.ArrayCollection;
		[Bindable]
		private var peopleColl:ArrayCollection = new ArrayCollection();

		[Bindable]
		private var buttonTitle:String = "Add Person";

		private var workflowState:String = "adding";

		private function submitPerson():void
		{
			if (workflowState == "adding")
			{
				addPerson();
			}
		}

		private function addPerson():void
		{
			var obj:Object = new Object();
			obj.firstName = firstName.text;
			obj.lastName = lastName.text;

			peopleColl.addItem(obj);
		}

		private function peopleLabelFunction(item:Object):String
		{
			return item.firstName + " " + item.lastName;
		}

		private function deletePerson():void
		{
			if (people.selectedItem != null)
			{
				peopleColl.removeItemAt(people.selectedIndex);
			}
		}
	]]>
</mx:Script>

We’ve added a buttonTitle and made it bindable, a workflowState variable so we know at what stage the application it at and a submitPerson() function that makes a comparison on the workflowState and triggers the addPerson() function if we are adding. Now we’ll change the add person button.

<mx:Button label="{buttonTitle}" click="submitPerson()"/>

So what have we done here? As far as functionality – nada. It’ll still work the same, but now we are using data bindings for the button title too. Whoopy do. Well actually it is.

However first things first I’ve actually been bad and not added some simple functionality to the form. Once we’ve added a person we need to clear the text fields

I’ll assume now you are familiar enough with the code I can simply show you the bits I’m adding or changing.

 private function addPerson():void
{
	var obj:Object = new Object();
	obj.firstName = firstName.text;
	obj.lastName = lastName.text;

	peopleColl.addItem(obj);

	firstName.text = "";
	lastName.text = "";
}

That’s a bit better.

Now for the editing functionality. First lets add some more binding. When the list is selected we want to populate the text fields with the selected item.

<mx:Form>
	<mx:FormItem label="First Name">
		<mx:TextInput id="firstName" text="{people.selectedItem.firstName}"/>
	</mx:FormItem>
	<mx:FormItem label="Last Name">
		<mx:TextInput id="lastName" text ="{people.selectedItem.lastName}"/>
	</mx:FormItem>
	<mx:Button label="{buttonTitle}" click="submitPerson()"/>
</mx:Form>

Now we’ve bound the text field properties to the items in the list. When the list is selected though we want to set the form to be an edit rather than add form. We’ll do that with this function.

private function doEdit():void
{
	workflowState = "editing";
	buttonTitle = "Edit Person";
}

This simply changes the buttonTitle, which if you remember is bound to the form button. And it sets the workflow state to editing. This means we can write the next part of our submit person function.

private function submitPerson():void
			{
	if (workflowState == "adding")
	{
		addPerson();
	}
	else if (workflowState == "editing")
	{
		editPerson();
	}
	else
	{
		//Err something really odd is happening here.
	}
}

And the actual edit function.

private function editPerson():void
{
	var obj:Object = peopleColl.getItemAt(people.selectedIndex);

	obj.firstName = firstName.text;
	obj.lastName = lastName.text;

	peopleColl[people.selectedIndex] = obj;

	people.selectedIndices = new Array();

	workflowState = "adding";
	buttonTitle = "Add Person";
}

So what’s happening here? First lets get the object from the array. Then change it’s properties of firstName and lastName to the text fields. Then put it back into the array where we got it from, effectively overwriting the item in the array. As the textFields are bound to the selected item of the people list we need to deselect the list, or we are going to be stuck in edit mode as the text fields will keep displaying the selected item. We cannot do firstName.text = “” as this would overwrite the binding we had set up and stop the app working as expected. If you set the selectedIndices of a list to a new Array this effectively deselects the list.

We are done editing so we set the workflow state to adding and the buttonTitle back to Add Person.

The final tweaks we need to make are in the delete function as you need to select the list before you can delete the person from it. This would then leave the application in edit mode and would stop it working as expected.

private function deletePerson():void
{
	if (people.selectedItem != null)
	{
		peopleColl.removeItemAt(people.selectedIndex);
		workflowState = "adding";
		buttonTitle = "Add Person";
	}
}

And finally, finally, lets put the validation code on to make sure that people at least enter something into the form.

private function addPerson():void
{
	if (firstName.text != "" || lastName.text != "")
	{
		var obj:Object = new Object();
		obj.firstName = firstName.text;
		obj.lastName = lastName.text;

		peopleColl.addItem(obj);

		firstName.text = "";
		lastName.text = "";
	}
	else
	{
		mx.controls.Alert.show("At least enter something, doofus.","No Details Submitted");
	}
}

You can see the finished app here.

Download the code from this link -> Simple Contact Form Complete MXML . The code is commented, so should be quite easy to read through.

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin

Flex Dynamic Data Binding 101 – Part Two

Sunday, 13. January 2008 20:26

OK, so we’ve covered the basics of data binding in part one. However you don’t have to use Actionscript to use data binding. This is a very quick example of how you can bind two components together without using Actionscript at all. Click here to see the example.

And this is the code :

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

	<mx:Label text="{input.text}"/>

	<mx:TextInput id="input" text="Type in here to change the label"/>

</mx:Application>

Simple you can get the code from this link -> Binding Components MXML Code.(Sorry, just moved the blog – examples back soon) Note that when binding components their properties are available for binding without using [Bindable] meta, this is only for Actionscript. This is a fairly useless example of data binding though. What may be useful would be to bind the enabled state of a button, for example a delete button, to the length of the array property of a list component. If the list component was empty, disable (or hide) the button. Or set the index of a view stack to the value of a radio group, or – er – OK this isn’t too useful. (Shorthand for – I’ve run out of good examples, lets get on and play with some more code.)

Next lets look at something that’s halfway towards a useful application of data binding.

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin

Flex Dynamic Data Binding 101 – Part One

Sunday, 13. January 2008 19:56

One of the really cool things you can do with flex is binding, or dynamic data binding, but I’ll just call it binding for now. At it’s most basic you can directly associate data with a view object, eg text input, without having to write the code that did it.

Suppose in Actionscript 2, or 1 for that matter, you had a dynamic text field with the instance name of ‘output_txt’.

Dynamic Text Field

There, I took a picture so you’d believe me. (The more eagle eyed of you will notice that this is actually Flash CS3).

If you had some data, in this case a string you wanted to display in this text field you’d write something like this.

var copy:String = "This is the copy.";

output_txt.text = copy;

And you’d display the copy. Fine, not too much code – what’s the problem?

The problem is that what if the copy has to be dynamic and change? What if the variable copy changes from “This is the copy” to “Disregard this information?” or “A zone one single is how much?” (I had to make a trip to London and am still wondering how anyone can afford it). The text input is a dumb component. It’s been told what its text property is, thankyou very much. If you want to change it, you’ll have to tell it to change the property. So in the function that returns the data, or changes the variable you’ve got to then reassign the variable to the text field

var copy:String = "This is the copy";
output_txt.text = copy;
function resetCopy()
{
 	copy = "Its costs nearly a fiver, why not take a cab, it's more comfortable and you've got more chance of getting where you want to."
	output_txt.text = copy;
}

Which is really just repeating yourself. And can become a real bore when you’ve got half a dozen (normally more) view components that are displaying data. Yes, you could write a function that is triggered every time a variable is changed (a listener), but invariably you’ll be checking which one has changed and then identifying which component that relates to and applying the change to that. You could be even more clever and use classes to have static functions that check your value objects (more classes basically) and update the view that way. (I’ll be doing some stuff on OOP – Object Orientated Programing soon)

However you do it as some point you will be saying this property (wot I already set) is equal to this variable (wot I’ve already said it was in the first place).

This is the point where dynamic data binding in flex really comes into it’s own. The process is really simple : -

  1. Create the variable you want to assign.
  2. Use the [Bindable] meta tag to let the compiler know that this variable is bindable – this allows us to access the variable with script on the component.
  3. Tell the view component what variable it has to bind to.
  4. That’s it.

Once it’s bound whenever the variable changes the component bound to updates too.

A simple example

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

 			creationComplete="resetString()">

 <mx:Script>

 	<![CDATA[

 		//Bindable metadata letting the compiler know the variable

 		//imediately afterwards is available for binding.  If you

 		//leave this off then you will get a compiler warning, but

 		//the code will still work...but just for me leave it in.

 		[Bindable]

 		public var copy:String = "This is the copy";

 		//Function called on Creation Complete.  This is triggered when

 		//the application has been launched, so after the copy variable

 		//was initially created.

 		public function resetString():void

 		{

 			//Reset the copy

 			copy = "I've changed."

 		}

 	]]>

 </mx:Script>

 <!--

 Here's the text input to display the variable.  The curly braces

 are required so the compiler knows to treat what is in them as Actionscript

  -->

 <mx:TextInput id="output" text="{copy}"/></mx:Application>

I’m not going to go through the code, there are comments and it should be quite self explanatory, you can down load the mxml from this link ->Simple Binding Example MXML File .(Sorry, just moved the blog – examples back soon EDIT : I lost it – I’ll get it back up ASAP – sorry!) The only things I will mention are :

Putting meta tags into Actionscript felt extremely alien to me when I first started and I didn’t really get them, however now I’m totally at ease with it so don’t worry if you start typing and think “What on earth is this all about?”

You HAVE to use the curly braces in the mxml or the compiler will not know it is supposed to be calling an Actionscript variable.

By the way if you run this you should get “I’ve changed.” in the text field. This proves that data binding is working as after reseting the variable we didn’t then go back to the text input component and reset the text property. Wow.
So? How was that? Totally underwhelmed? Don’t worry this is just the principles, next we’ll look at how you can bind components together with no code whatsoever.

Flex Dynamic Data Binding 101 – Part Two

Category:Basic Code, Flex, Tutorials | Comment (0) | Author: admin