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

17 reacties:
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)
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.
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!
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!
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
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.
Do You interesting of [b]Viagra 100mg dosage[/b]? You can find below...
[size=10]>>>[url=http://listita.info/go.php?sid=1][b]Viagra 100mg dosage[/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 Viagra 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][/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 its cool sites common
[url=http://www.pi7.ru/zdorove/1537-yaponcy-sozdali-pivo-bez-edinoy-kalorii.html ]Если не сплетничать,то о чем говорить? [/url]
Встречаемся с парнем 7 месяцев (мне 29,парню 28,дева )) ) . Все у нас хорошо и любим друг друга . Ездили сообща на отдых (на неделю) . Каждые выходные я остаюсь у него. Пыталась издали вывести на диалог по поводу будущего . Его ответ : " Я об этом еще даже и не думал. Мне хорошо с тобой и я этим наслаждаюсь." Но однажыд,произошла размолвка и он мне сказал : " Ты от меня чего-то ждёшь. Но я не могу тебе этого уяснить. Я не могу стать еще больше нежным и внимательным . И мужем я твоим не стану " . Он меня шокировал этим высказыванием . Но так как он мне не давал никаких обещаний и надежд ,поэтому мой шок еще быстро и прошёл )) . Мы встречаемся до сих пор . Недавно я прожила с ним 2 недели . Все было хорошо и замечательно. Казалось ыб,ну что еще нужно ... ?? Когда эти 2 недели подошли к концу,он не захотел,чтобы я уходила ,но и не остановил ...Просто сказал :"Может еще останешься на неделю,а там видно будет ...." Я подумала,что это удобный момент поговорить о будущем.. Что и увуие у кого мысли/планы. Моё стремление для совместного проживания очень велико,но он вроде и не против ,но в также время (из его слов) ,еще не готов ... боится потерять свой блеск личное пространство и т.д. ...Конечно,я почитаю его стремление и в следствии этого согласилась с тем,что он еще не готов и ему надо время на это созреть .. но,произнесённая им фраза " ЧТО Я И МУЖЕМ ТВОИМ НЕ БУДУ" чётко подчёркивает его неготовность или же ..... нежелание быть со мной... Подскажите,как мне поступить ?? М ылюбим друг дуга ,но вот эти его слова меня натсараживают и забирают уверенность в завтрашнем дне
Как говорилось на Seexi.net Мужской взгляд на дамскую прозу - жизни...
Сначала некое пояснение по поводу такого, как я (мужчина) взялся писать дамскую прозу…
Хотя… так, наверное, не обязано быть, всё-таки женская проза подразумевает - дамский взгляд на… Да на всё что угодно! И вот решил я попосмотреть своим мужским взглядом на всякие женские… штучки-дрючки… сопровождающие жизнь великолепной половины человечества...
Данное проведение (История про Ксюшу и её подруг) можно расценивать как иронию, а можно и как пародию на дамскую прозу, однако, серьёзного в этом тексте в иных местах даже побольше, чем есть в самых серьёзных романах...
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.
Однако, афтар грамотно накреативил!
Разместил на своем народовском сайте ссылку на этот пост. Думаю, многим будет интересно!
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 );
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.
Thanks mate... just dropped by. Will look for BIKE STN when we get to Seattle. Still in Buenos Airies.
this post really very good and effective for me thanks for sharing this nice post
Een reactie plaatsen