zondag, november 18, 2007

Flex components in Flash: Example with source

Here's how to load a Flex component in Flash and communicate with it through events.
This can be pretty nifty if you want to use the much better components that ship with Flex in your Flash application.

Click here to see it in action.
This example uses a simple button, but you could use a more complex datagrid if you'd like.

Here's the flow:

1. Load the Flex swf into your flash
2. Wait until the loaded Flex component reaches frames 2 (all Flex swf's have 2 frames indeed)
3. Add the eventlistener (for the event defined in the flex) on the application property of the loaded object. This property is actually a property of the SystemManager class. Remeber the SystemManager class does not exist in Flash. It's a Flex thing.

Here's some sample code to use in Flash:

import flash.display.*;
import flash.events.*;
import flash.net.URLRequest;
import flash.utils.Timer;

var loader:Loader = new Loader();
var timer:Timer;
//load the Flex Component
loader.load(new URLRequest("ButtonTest.swf"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderDone);
addChild(loader);

function loaderDone(e:Event) {
timer = new Timer(100);
timer.addEventListener(TimerEvent.TIMER, handleTimer)
timer.start();
}


function handleTimer(event:TimerEvent):void {
//cast the loader.content into MovieClip to access currentFrame.
var myclip:MovieClip = loader.content as MovieClip;
if (myclip.currentFrame == 2) {
//use application property to attach the event listener
myclip.application.addEventListener("iAmClickedFromFlex", clickedFromFlex);
timer.stop();
}
}

function clickedFromFlex(event:Event):void {
trace("clicked");
}


Flex code: (just a simple button)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Button x="5" y="20" label="I am a flexbutton" click="dispatchEvent(new Event('iAmClickedFromFlex'))"/>
</mx:Application>


This message has also been posted on Boulevart labs

58 opmerkingen:

Anoniem zei

Hi, Wim,

I loved your example and the tutorial videos of how you combine flash and flex - I'm really trying to find a flash-centric way to use the latest gen tools on my stuff (http://gingerbooth.com - mostly science teaching simulators).

But - I got that flex button to work in a Flash movie. But - I put it into a Flash movie that already had a slew of Flash components in it (my attempts to reconstruct v2 haloOrange menuBar and...) The flex button works. But with that loaded, all the Flash CS3 components become inert - no mouseovers, no clicks, nothing. It's pretty boolean - comment out the load-flex-button, and the components work. Uncomment the load-flex-button, and the other components are dead artwork.

What I'm actually trying to do is find a way to use charts in Flash CS3...

Any insights you could offer would be *so* welcome!

- Ginger Booth (ginger at gingerbooth.com)

Tom zei

Ginger, I've run into the exact same problem. Apparently Flex creates an invisible layer that covers the whole stage (mx.managers.SystemManager), which catches all events such as mouse clicks that are not caught by any other Flex components. This only happens on the root Flex swf that's loaded, and any other swf's that are loaded on top of it recognize the first Flex application as their root, and won't create a new SystemManager layer.

The Flex swf does not know or understand that it is loaded by a Flash SWF, because Flash does not have access to the Flex SDK, so it does create the SystemManager, rendering all components in the underlying Flash useless. This SystemManager is not addressable, so there is no way you can disable it or anything.

What I currently do, is create a Flex wrapper application, which then in turn loads the main Flash SWF. Since the SystemManager is created in the wrapper Flex SWF, any other SWF's or Flex components will recognize this and not create a new SystemManager.

Wim Vanhenden zei

Hi Ginger and Tom,

Thanks for the reactions and questions. I have only used this as a test so I have never really implemented it in a real life case.

Tom, your solution seems to be a good one but actually it becomes more of a Flex project instead of a Flash project.

I guess it's not feasable (at the moment) to use the Flex components in conjuction with Flash components in a Flash project.

I hope in the future Adobe will support Flash developers more when it comes to using some of the Flex advantages in Flash.

I am currently working on a post about using Flex to compile swf's with embedded fonts and then use them in Flash. More on that soon.

Thanks a lot!

CreativeSauce zei

Thanks for your example!

It did great help to me!

Finally managed to get the Flex compiled swf to be loaded into Flash swf and the communication between both main and loaded Flex swf done.

When I am doing this, I just want to share one problem that I faced, after declaring a new Loader Class to load in the Flex swf, you need to addChild the new Loader Instance onto the stage immediately, instead of complete loading the external flex swf then add it onto the stage. I guess is probably flex require to reference to the stage during it initialization else you would get an error message.

Cheers!

Thanks!

flex and flash zei

If interested in inverse way:
Integrating Flash MovieClip inside Flex you can see at

http://programmaremobile.blogspot.com/2009/10/make-gui-with-flash-and-code-by-flex.html

Anoniem zei

Do You interesting of [b]Female use of Viagra[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Female use of Viagra[/b][/url]<<<[/size]

[URL=http://imgwebsearch.com/30269/link/buy%20viagra/1_valentine3.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/1_valentine3.png[/IMG][/URL]
[URL=http://imgwebsearch.com/30269/link/buy%20viagra/3_headsex1.html][IMG]http://imgwebsearch.com/30269/img0/buy%20viagra/3_headsex1.png[/IMG][/URL]
[b]Bonus Policy[/b]
Order 3 or more products and get free Regular Airmail shipping!
Free Regular Airmail shipping for orders starting with $200.00!

Free insurance (guaranteed reshipment if delivery failed) for orders starting with $300.00!
[b]Description[/b]

Generic Viagra (sildenafil citrate; brand names include: Aphrodil / Edegra / Erasmo / Penegra / Revatio / Supra / Zwagra) is an effective treatment for erectile dysfunction regardless of the cause or duration of the problem or the age of the patient.
Sildenafil Citrate is the active ingredient used to treat erectile dysfunction (impotence) in men. It can help men who have erectile dysfunction get and sustain an erection when they are sexually excited.
Generic Viagra is manufactured in accordance with World Health Organization standards and guidelines (WHO-GMP). Also you can find on our sites.
Generic [url=http://viagra.opuskali.ru]Viagra Super Active[/url] is made with thorough reverse engineering for the sildenafil citrate molecule - a totally different process of making sildenafil and its reaction. That is why it takes effect in 15 minutes compared to other drugs which take 30-40 minutes to take effect.
[b]viagra side effects warnings
female viagra for men
Erowid Viagra
Viagra Soft
Viagra Use For Women
cost cialis viagra
viagra penis enhancer videos
[/b]
Even in the most sexually liberated and self-satisfied of nations, many people still yearn to burn more, to feel ready for bedding no matter what the clock says and to desire their partner of 23 years as much as they did when their love was brand new.
The market is saturated with books on how to revive a flagging libido or spice up monotonous sex, and sex therapists say “lack of desire” is one of the most common complaints they hear from patients, particularly women.

blogku adalah ladang uangku zei

blogku adalah ladang uangku its cool sites common

Anoniem zei

[url=http://www.pi7.ru/zdorove/1537-yaponcy-sozdali-pivo-bez-edinoy-kalorii.html ]Если не сплетничать,то о чем говорить? [/url]
Встречаемся с парнем 7 месяцев (мне 29,парню 28,дева )) ) . Все у нас хорошо и любим друг друга . Ездили сообща на отдых (на неделю) . Каждые выходные я остаюсь у него. Пыталась издали вывести на диалог по поводу будущего . Его ответ : " Я об этом еще даже и не думал. Мне хорошо с тобой и я этим наслаждаюсь." Но однажыд,произошла размолвка и он мне сказал : " Ты от меня чего-то ждёшь. Но я не могу тебе этого уяснить. Я не могу стать еще больше нежным и внимательным . И мужем я твоим не стану " . Он меня шокировал этим высказыванием . Но так как он мне не давал никаких обещаний и надежд ,поэтому мой шок еще быстро и прошёл )) . Мы встречаемся до сих пор . Недавно я прожила с ним 2 недели . Все было хорошо и замечательно. Казалось ыб,ну что еще нужно ... ?? Когда эти 2 недели подошли к концу,он не захотел,чтобы я уходила ,но и не остановил ...Просто сказал :"Может еще останешься на неделю,а там видно будет ...." Я подумала,что это удобный момент поговорить о будущем.. Что и увуие у кого мысли/планы. Моё стремление для совместного проживания очень велико,но он вроде и не против ,но в также время (из его слов) ,еще не готов ... боится потерять свой блеск личное пространство и т.д. ...Конечно,я почитаю его стремление и в следствии этого согласилась с тем,что он еще не готов и ему надо время на это созреть .. но,произнесённая им фраза " ЧТО Я И МУЖЕМ ТВОИМ НЕ БУДУ" чётко подчёркивает его неготовность или же ..... нежелание быть со мной... Подскажите,как мне поступить ?? М ылюбим друг дуга ,но вот эти его слова меня натсараживают и забирают уверенность в завтрашнем дне

Anoniem zei

Как говорилось на Seexi.net Мужской взгляд на дамскую прозу - жизни...
Сначала некое пояснение по поводу такого, как я (мужчина) взялся писать дамскую прозу…
Хотя… так, наверное, не обязано быть, всё-таки женская проза подразумевает - дамский взгляд на… Да на всё что угодно! И вот решил я попосмотреть своим мужским взглядом на всякие женские… штучки-дрючки… сопровождающие жизнь великолепной половины человечества...
Данное проведение (История про Ксюшу и её подруг) можно расценивать как иронию, а можно и как пародию на дамскую прозу, однако, серьёзного в этом тексте в иных местах даже побольше, чем есть в самых серьёзных романах...

viagra generic online zei

Hello,
This is really amazing informaiton about Flash..... Thanks for the share.... It's getting helpful to all the programmers and graphics designers. Keep posting such an interesting posts.

Anoniem zei

Однако, афтар грамотно накреативил!

Anoniem zei

Разместил на своем народовском сайте ссылку на этот пост. Думаю, многим будет интересно!

Thijs zei

Instead of the Timer approach and checking for the 2nd frame you could also listen for the 'applicationComplete' event instead, i.e.:

_flexApp = _loader.content as MovieClip;
_flexApp.addEventListener( "applicationComplete", onDefaultStyleInit );

business logo design zei

Your creations is really good. It was amazing,the way you project your innovative ideas helps a lot. Hope to read more post from you.

buy viagra online zei

Thanks mate... just dropped by. Will look for BIKE STN when we get to Seattle. Still in Buenos Airies.

viagra oral zei

this post really very good and effective for me thanks for sharing this nice post

Anoniem zei

xanax for sale xanax white pill 027 - xanax side effects .5mg

Anoniem zei

Post34, http://www.arlo.net/massacree/ viagra online in uk, gxie2, http://www.arlo.net/fccgb/ order viagra without prescriptions, alcy5, http://www.arlo.net/fccgb/notes/ generic viagra uk, egov5, http://www.arlo.net/bytes/ viagra cheap, hfug0, http://www.arlo.net/live/ viagra for sale

Anoniem zei

Hi www.blogger.com owner, are you interested in links exchange? Reply to my email
[url=http://www.youtube.com/watch?v=xikJ5Z55nRU]Unlock Nokia Lumia 920[/url]
[url=http://www.youtube.com/watch?v=LBQ-by4Hvls]Unlock Nokia Lumia 820[/url]
[url=http://www.youtube.com/watch?v=AA4dnhedRE8]Unlock Sony Xperia T[/url]

Anoniem zei

How to unlock your nokia for free
[url=http://www.youtube.com/watch?v=24CDKB--424]Unlock Nokia 6121 classic[/url]
[url=http://www.youtube.com/watch?v=sQpRPPQ5y6s]Unlock Nokia 3606[/url]
[url=http://www.youtube.com/watch?v=f3jH_ddZCdI]Unlock Nokia 6205[/url]

Anoniem zei

A lot of quality articles i see on your www.blogger.com
[url=http://www.youtube.com/watch?v=VrzEBsSUua4] Unlock Nokia 8600 Luna[/url]
[url=http://www.youtube.com/watch?v=byULxQczD0E] Unlock Nokia 6650 Fold[/url]
[url=http://www.youtube.com/watch?v=jicGWSKN8FA] Unlock Nokia C3 01[/url]

Anoniem zei

www.blogger.com owner you are great

[url=http://luv-2-share-pics.tumblr.com]click here[/url]

Anoniem zei

[url=http://loveepicentre.com/success_stories.php][img]http://loveepicentre.com/uploades/photos/3.jpg[/img][/url]
skovde sweden dating [url=http://loveepicentre.com/faq.php]stewart and patt dating[/url] who is bruno mars dating
sex personals dating nc w4m [url=http://loveepicentre.com/taketour.php]dating site to find russian woman[/url] before radiometric dating
asian girl dating [url=http://loveepicentre.com/]alska native indian women dating[/url] romance china romances lover dating

Anoniem zei

ebook teacher http://audiobooksworld.co.uk/Christophe-Dabancourt/m20770/ insert links in your ebook [url=http://audiobooksworld.co.uk/The-Alchemy-of-Finance/p22044/]zombie ebook[/url] free ebook download on islam

Anoniem zei

Салон Секреты Красоты предлагает большой выбор классических салонных услуг: парикмахерские услуги, маникюр, педикюр, косметология, перманентный макияж. Мы работаем более 10 лет и придерживаемся принципа соотношения цены и качества обслуживания. Для постоянных клиентов действуют акции и бонусная система. Заходите на наш сайт [url=http://s-krasoti.ru/] педикюр фрунзенская
[/url]

Anoniem zei

Best adult pay per click

[url=http://www.youtube.com/watch?v=QdRWd3nJFjE]adult ppc[/url]

Anoniem zei

Are you searching for [url=http://bbwroom.tumblr.com]BBW pictures[/url] this website is the right place for you!

Anoniem zei

Szukasz seksu bez zobowiazan ? Najwiekszy portal randkowy dla doroslych, zajrzyj do nas

anonse kobiet

Anoniem zei

Once you've motivated which financial loan is right for you and possess sought the recommendations of an SBA loan professional, where don't you begin. This will influence benefits are available is deal with urgent matters is Immediate cash Advance Payday cash loans in British. An alternate way to get one of your no fax absolutely no credit check payday cash loans is to head to an actual shop in your area. learn more Fill in the straightforward application form and will also be college degree, duty online transfer need of the money in the course of unexpected emergency.

Anoniem zei

Payday loan lenders are very aware that poor situations eventually all of us every once in awhile through no-fault of our own. Expense on faxing documents- It really is well noted in which fast lending options are your close friends that can assist you to through crisis situations. To fight next to harassment, statement any suspect or outlawed facing short money returned over a limited time? fast same day loans It's also damaged when you get a new credit card or maybe get instant credit in a department store.

Anoniem zei

Hi there! I understand this is sort of off-topic but I had
to ask. Does running a well-established blog such as yours require a large amount of
work? I am brand new to operating a blog however I do write in my
diary everyday. I'd like to start a blog so I can share my own experience and thoughts online. Please let me know if you have any ideas or tips for new aspiring bloggers. Appreciate it!

Feel free to visit my blog post ... http://www.converseshopfr.com/

Anoniem zei

Hey There. I discovered your blog the usage of msn. This is
an extremely smartly written article. I will be sure to bookmark it and come back
to learn more of your helpful info. Thank you for the post.
I will definitely return.

Feel free to visit my homepage; Louis Vuitton Bags

Anoniem zei

Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you!
However, how can we communicate?

Also visit my web page - visit this link

Anoniem zei

Very good article. I'm going through a few of these issues as well..

My web blog ... http://slc-wireless.com

Anoniem zei

After going over a number of the blog articles on your blog,
I truly like your way of blogging. I saved it to my bookmark
website list and will be checking back soon. Please visit my website as well
and tell me how you feel.

Feel free to surf to my web blog ... ABC Personal Financing

Anoniem zei

When some one searches for his essential thing,
so he/she wants to be available that in detail, so that
thing is maintained over here.

Here is my blog :: Cheap Oakley Sunglasses

Anoniem zei

Howdy great blog! Does running a blog similar to this require a large amount of work?
I have virtually no understanding of programming but I was
hoping to start my own blog in the near future.
Anyway, if you have any recommendations or techniques for
new blog owners please share. I understand this is off topic but
I simply had to ask. Many thanks!

my weblog ... Louis Vuitton Pas Cher

Anoniem zei

Pretty nice post. I just stumbled upon your blog and wished
to say that I've truly enjoyed browsing your blog posts. After all I'll be subscribing to your feed and I hope you write again soon!



Feel free to visit my page - Authentic Evgeni Malkin Jersey

Anoniem zei

I am regular reader, how are you everybody? This post posted at this web page is really nice.


Here is my homepage :: Louis Vuitton Bags

Anoniem zei

What's up, the whole thing is going sound here and ofcourse every one is sharing data, that's really good, keep up
writing.

Here is my homepage ... Air Jordan

Anoniem zei

Wow, that's what I was looking for, what a material! present here at this web site, thanks admin of this site.

Here is my web page: Louis Vuitton Bags

Anoniem zei

Hi, i believe that i noticed you visited my blog thus i got here to go back the
choose?.I'm trying to in finding issues to improve my web site!I guess its adequate to make use of a few of your ideas!!

Feel free to visit my weblog; Go Here

Anoniem zei

For newest news you have to visit world wide web and on internet I found this
web page as a best web page for newest updates.

Here is my web blog: Authentic Mario Lemieux Jersey

Anoniem zei

Excellent article. Keep writing such kind of info on your
site. Im really impressed by your site.
Hello there, You have performed a great job. I will definitely
digg it and for my part suggest to my friends. I'm sure they'll be benefited from this site.


Also visit my web site :: Abercrombie

Anoniem zei

This is really interesting, You are a very skilled blogger.
I have joined your feed and look forward to seeking more of
your excellent post. Also, I have shared your site in my social networks!


my web blog: Michael Kors Outlet

Anoniem zei

Right now it appears like Drupal is the best blogging platform out there right
now. (from what I've read) Is that what you are using on your blog?

Feel free to visit my homepage: Abercrombie France

Anoniem zei

Your style is very unique in comparison to other folks I've read stuff from. Thank you for posting when you've
got the opportunity, Guess I will just bookmark this
blog.

my web-site ... get more info

Anoniem zei

Have you ever considered about adding a little bit more than just your
articles? I mean, what you say is fundamental and everything.
But imagine if you added some great images or videos to give your posts more,
"pop"! Your content is excellent but with pics and clips, this site could undeniably be one of the very best
in its field. Awesome blog!

Look at my web blog: Boutique Air Max

Anoniem zei

Aw, this was a really good post. Taking the time and
actual effort to generate a top notch article… but what
can I say… I hesitate a lot and don't seem to get nearly anything done.

Here is my homepage - Louis Vuitton Handbags

Anoniem zei

No matter if some one searches for his vital thing,
so he/she wants to be available that in detail, thus that thing is maintained over here.



my blog :: Louis Vuitton Handbags []

Anoniem zei

Very good blog! Do you have any tips and hints
for aspiring writers? I'm planning to start my own blog soon but I'm a little lost on everything.
Would you suggest starting with a free platform like Wordpress or go for a paid option?

There are so many options out there that I'm totally confused .. Any recommendations? Thanks a lot!

Stop by my blog post :: Boutique Air Max

Anoniem zei

Heya i am for the first time here. I found this board and I to find It truly useful & it
helped me out much. I'm hoping to offer one thing again and aid others such as you helped me.

my blog - Chaussures De Foot Pas Cher

Anoniem zei

My spouse and I stumbled over here different page and thought
I may as well check things out. I like what I see so
now i am following you. Look forward to going over your web page
repeatedly.

Feel free to visit my web-site :: Chaussures De Foot Pas Cher

Anoniem zei

I was able to find good advice from your blog posts.


Here is my web blog: Nike Free Tilbud ()

Anoniem zei

Hello There. I discovered your weblog using msn. This is a really smartly written article.
I'll be sure to bookmark it and return to learn more of your helpful information. Thanks for the post. I'll
certainly return.

My weblog: Wholesale Jerseys

Anoniem zei


Cialis Online [url=http://www.domca.com/lib/buycialis/]Buy Cialis [/url]http://www.domca.com/lib/buycialis/

Anoniem zei

It's appropriate time to make some plans for the future and it's time to be happy.
I've read this post and if I could I wish to suggest you some interesting things or tips. Maybe you can write next articles referring to this article. I desire to read even more things about it!

Here is my blog - Boutique Air Jordan

Anoniem zei

Your style is unique in comparison to other people
I have read stuff from. Thank you for posting when you've got the opportunity, Guess I will just book mark this page.

Here is my homepage ... Nike Blazers JD