view source

Using the Delegate class to manage scope

October 25th, 2007 . by polyGeek
Download code samples

The Delegate class is used to specify the scope that a method/function operates in. It’s primary use is for Flash components and managing the events they dispatch. I personally don’t use the Flash components so I never came across it. If you’ve never heard of it either then get ready for a really cool addition to your coding toolbox.

Suppose you are creating a setInterval. You would do something like this:

That’s pretty much the way I always create intervals. When you run it you’ll get undefined for this.

The other way to create an interval is like this:

That solves the problem of scope in the function call. But there’s yet another way:

The Delegate class is like a Jedi mind trick for methods/functions. It says, “this is not the scope you are running in. Use this one instead.”

The only downside I can find with using Delegate is that you can’t pass arguments to the method/function that you call. At least I can’t find any documentation on that.

Note: a reader commented below that there is a way of using the Delegate class, or something like it, that does allow for passing parameters. Here is the link: person13.com/articles/proxy/Proxy.htm

Using the Delegate in this example is a little more code to write for the same result as the second approach but this isn’t really what Delegate was meant for.

setIntervals could get a little messy when you’re using them inside classes. You pretty much had to create nested functions so that you would be able to clear the interval later. Or the setInterval number could be a property of the class but that comes with it’s own baggage.

In my book this is where Delegate really shines.

That is a nice clean way to create methods that can be run on an interval and cleared when wanted.

Making Mouse listeners

When you create a Mouse Listener the scope of the function callback is the object that is listening to the Mouse events. And that’s usually not the scope you want to run in because it’s sort of like an island in the middle of a huge ocean.

The standard Mouse listener looks like this:

You’re sort of left hanging on the scope of the MouseListener1 object there. Not a whole lot of good. Using Delegate we can make that function run in any scope we want to. For this simple example it will run in the scope of the _root.

Another solution is to attach the scope that you want to the listener object like this:

That’s pretty much the way I did things before learning about Delegate. This approach works fine for most occasions. In my estimation the best reason for using Delegate is that it’s just more elegant. Using this.thisRef seems like a bit of a hack to me. Although I’ve used it countless times.

Creating Interface elements

Here’s an example of how you might use Delegate in a class where you are creating user interface elements, otherwise known as buttons. :-)

In this class I create a simple button. I pass along a MovieClip to create the visual elements inside of, the button label, the width and height of the button, and weather to use Delegate to manage the onRelease event or attach a reference to the button instance via thisRef.

The basic problem when creating interactive elements in a class is that when the user clicks on one of them the scope is automatically the MovieClip they just clicked on. Not the class that created the button in the first place. That’s where the data, or access to the data, would be handled.

There are numerous ways to handle this problem. You could create static methods in a class and pass along information. And you can dynamically attach properties to the MovieClip when it’s created. In that way it can identify itself. But it can’t get access to the instance of the class that created it without attaching this inside the class, as I did with the Mouse listener above.

By using Delegate you can make the button operate in the scope of the the class instance which created it. That can be very handy. The downside is that now you’ve lost reference to the actual MovieClip that was clicked on. That can be solved very simply by keeping a reference to the MovieClip as a class property.

Here is an example:

You can see that with this class you can either use Delegate or attach this to the Button instance. Here’s an example of two instantiations that use the two approaches.

No need for Delegate in Actionscript 3

The good news is that in Actionscript 3 events are handled completely differently, or should I say correctly. In Actionscript 1/2 events were sort of added willy-nilly to the language/player over time. With Actionscript 3 we can create classes and get event objects sent to the callback. Essentially scope is much easier to handle. But that’s another story.

You can read more about the Delegate class and components at Actionscript.org.


Gradient Masks in Flash

October 23rd, 2007 . by polyGeek

To create a gradient mask in Flash apply bitmap caching to each of the mask and maskee MovieClips and then use setMask() to apply the mask. As such:maskMC.cacheAsBitmap = true;
img.cacheAsBitmap = true;
img.setMask( maskMC );

Here’s an example:

Download FLA

WhatDoIKnow.org has a nice writeup with comments on the topic. By the way, you can do this same effect without code but it seems like a lot more work to me.

I only need to do this about once a year and I always end up spending an hour going, “how the frak did I do that last year.” Now next year when I need to do this again I can just search my own blog. If I remember that I wrote about this. :-)


Flash Context Menu doesn’t allow ‘delete’

October 19th, 2007 . by polyGeek

While doing a prototype for a usability study I was asked to customize the context menu when a user right-clicked on a specific button. No problem except one of the custom menu options they wanted was “Delete”.

Everything worked in the context menu as you might expect except everything after the “Delete” was, well, deleted. And it wouldn’t display the “Delete” either. I kept checking my code to see if there was some silent failure I wasn’t seeing and then it occurred to me, “Maybe it doesn’t like the word “Delete”.

Sure enough, that was it. Change “Delete” to anything else and it works.

Below is the code that I used: ( download source )


It’s a small, small web afterall

October 19th, 2007 . by polyGeek

A few weeks ago I got an email from a woman who lives in Ontario Canada. She told me that she had a problem with a program she had purchased and asked if I could help her. Here is what she wrote:

Hi Dan.I found your site and am hoping someone can help with a problem.I have bought the full version of SmileBox. I loved making scrapbooks and emailed them to my friends. Now I have a problem. When I try to send a smile card I get a message that says problem sending creation. I wrote to the company who then sent me three pages of instructions. I am a senior and not that great on computers. I did install the program Flash like they said. They said to uninstall Flash but I couldn’t find it anywhere on my computer. I have cable internet and have no problem with it except with SmileBox. I love the program and have paid for one year. Can you help with this ? I would really appreciate it. Nicole from Ontario canada.

What baffled me about this email is that I didn’t recall making any public announcements that I was going to work at SmileBox.com. I had accepted an offer and was about to start working there one week later.

I did a Google site-search on my blog wondering if I had made mention of it somewhere unknowingly. But no. Searching my site for SmileBox returned no results.

I did a site-search at SmileBox to see if they had already added me to their contact page or something. But no results there either.

So I replied and told her that I had not started working at SmileBox yet but that I would help her get everything working for her again. And then I asked her how it was that she knew to contact me.

In her reply she told me that she found my site after searching for uninstalling Flash. She made no connection between me and SmileBox.com. It was just a coincidence. A very big one.

I did a Google search for uninstalling Flash smilebox and sure enough. Polygeek.com pops up on page two of the results.

One of my favorite quotes is, “Million to one odds happen 5 times a day in New York City.”

I guess billion to one odds must happen once a day on the web.


The FlexShow : three great reasons to listen

October 18th, 2007 . by polyGeek

TheFlexShow.com has the first of a two parter discussion about the Adobe MAX 07 conference in Chicago. The three great reasons to listen to the discussion are that Ryan Stewart and Jeffry Houser do their usual great job of hosting and Tony Hillerson, of EffectiveUI.com has some great comments and insights that he shares.

Between the three of them they pretty much make up for the fact that I’m also there leading the discussion astray from time to time and mumbling in the background. The show is worth listening to if you want a good overview of the MAX/Chicago conference.


Optimized code could help reduce global warming

October 15th, 2007 . by polyGeek
Bloggers Unite - Blog Action Day

Everyone wants to optimize their code so that it will perform faster and give the user a smoother more entertaining experience with their RIAs and cool 3D sites created with Papervison3D. But have you ever stopped to think that by its very nature optimized code uses fewer CPU cycles and therefore less energy. In doing so you reduce the amount of carbon dioxide in the atmosphere.

So here are a few tips to optimize your code and save a few icebergs in the process.

When iterating through an array you should declare the length of the array outside of the for-loop as such:
var len:int = someArray.length;
for( var i:int = 0; i < len; i++ ) {...

You can apply that to AS2 by declaring len as type Number.

In AS3 never use Math.floor. It’s slow as frak. Instead cast the number as a type int as so:
var someDecimalNumber:Number = 3.14159265
var someNumber:int = int( someDecimalNumber );

And my favorite is instead of dividing you should multiply by a decimal as such:
var halfWay1:Number = ( endX - startX ) / 2; // slow
var halfWay2:Number = ( endX - startX ) * 0.5 // fast

Or if you really want to burn rubber then when multiplying or dividing by 2 you can use the binary right or left shift operator. As such:
var half:Number = 123 >> 1; // same as dividing by two
var twice:Number = 123 << 1; // same as multiplying by two

Note: using right-shift to divide outputs an integer so it only works accurately with even numbers. Example 7 >> 1 = 3.

There are lots more great ideas here at OSflash.

Now go out there and write optimized code. If not for your users then think of the polar bears.


Flex Testing : Don’t do it in your default browser

October 13th, 2007 . by polyGeek

This might seem rather obvious to most of you, it did to me once I thought about it, but don’t use your default browser for testing/debugging your Flex apps.

Why?

Because you’re likely to crash your browser. I know I do all the time.

To select which browser Flex Builder/Eclipse uses for testing and debugging open up your preferences: Window -> Perferences. Then in the left navigation panel open up General -> Web Browser.

FlexBuilder WebBrowser Preferences

I’m sure I’m not the only one who screws up the logic on their do-while loops or recursive function calls. So now while you’re waiting for the Flash player to timeout and let you stop the script you can browse through your unread RSS feeds in your default browser. :-)


FlexBuilder Error : VerifyError: Error #1053

October 12th, 2007 . by polyGeek

I’m getting the following error when I use the FlexProjectWizard to create a project that will access data through ColdFusion Flash Remoting Service:

VerifyError: Error #1053: Illegal override of subtopic in mx.messaging.Consumer.
at flash.display::MovieClip/nextFrame()
at mx.managers::SystemManager/::deferredNextFrame()
at mx.managers::SystemManager/::preloader_initProgressHandler()
at flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/::timerHandler()
at flash.utils::Timer/flash.utils:Timer::_timerDispatch()
at flash.utils::Timer/flash.utils:Timer::tick()

Solution ( well it worked for me )

Remove the Library path to the fds.swc file and just leave it as: \WEB-INF\flex\libs\.

FlexBuilder_error



You can also find some help on the Flex Support Forums.

Ask me why it works this way? Go on, ask…

Reply: I don’t know! I didn’t build the frakking thing!!! ( Reese in Terminator. I love that line. I use it a lot at work. )


Adobe Ads component idea

October 11th, 2007 . by polyGeek

Of all the components that are supplied by Adobe the one that is missing is an Ads component. Something we can drop into our Flex/AIR apps to display ads and make some money off our work.

Here’s how I would see it working:

  • I would sign up with Adobe, just as I would with Google Ads, for an affiliate account
  • Then all I need to do is place the ad component in my app and give it my affiliate number
  • I could also use data binding to feed it keywords to target the ad content
  • I could specify certain ad attributes: media type - text, Flash, video, etc.
  • Both me and Adobe Make some money

The component would also need to know if it’s in an AIR app and if so then cache some ads in case the user is offline. Then if the user clicks on an ad in offline mode the component would have to store that click and inform the user that they will get more info when they go back online. Or something like that.

The upshot is that Adobe becomes an ad server and will make money off it. Plus we developers will be able to easily place ads in our work and make some money so that we won’t have to work for the man.

Yes, you could do this would Google ads but it would take some work. Wouldn’t you rather have a nice component built by Adobe?


Nerd Score

October 10th, 2007 . by polyGeek


NerdTests.com says I'm a Cool Nerd King. What are you? Click here!

I think I’ll create polyGeek test. In Flex of course. ;-)

Hey Sim: my nerd-fu is greater than your nerd-fu!


« Previous Entries    




© Copyright 2008 polyGeek.com / Dan Florio, All Rights Reserved Except Where Explicitly Stated
Web Developement Blogs - Blog Catalog Blog Directory
M2 Websites