问题
I'm having trouble with updating a var and firing a function with it on creationcomplete.
In the main component i declared a var artist. This var certainly works and has a value. I also need that var in another component: a profile component. I am able to get that var with:
newVar = Maincomp(this.parentApplication).artist;
I use the newVar in an API in the profile component. When i launch the API function with a mouseEvent, it works. However, i want to launch the API function on creationComplete and than the var doesn't work: it returns Null. I hoped that making all the involved vars bindable would help, but it doesn't. How can this be fixed?
Extra code to make my case clearer:
In main comp:
public function handleclick(cName:String):void
{
vName = "aVariableIGetFromAnAPI";
}
in profile comp:
public function zoekImages(event:FlexEvent):void
{
var api_URL:String = 'http://ws.audioscrobbler.com/2.0/';
var api_imagemethod:String = 'artist.getImages';
var api_key:String = '99f1f497c0bd598f1ec20571a38e2219';
artistImage = DifficultierAPI(this.parentApplication).vName;
var autocorrect:String = '1';
var limit:String = '4';
api_imagerequest = api_URL + '?method=' + api_imagemethod + '&artist=' + artistImage + '&autocorrect=' + autocorrect + '&api_key=' + api_key + '&limit=' + limit;
imageRequest.send(); // hier maak je connectie met lastfm
}
This code works, but point is that this code works if i call it with a MouseEvent, but doesn't when it needs to launch on creationcomplete. Or well, it returns Null instead of a value. I thought that making the involved vars bindable would fix it, but it doesn't. Any help?
回答1:
If you're looking to bind the variable all along from the main application to the nested component, simply declare a variable as public and bindable within your component :
Main application
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" xmlns:Components="Components.*">
<fx:Script>
<![CDATA[
[Bindable]
public var myMainVar:String;
protected function button1_clickHandler(event:MouseEvent):void
{
myMainVar = "Hi there!";
}
]]>
</fx:Script>
<s:layout>
<s:VerticalLayout/>
</s:layout>
<s:Button label="Click me to update the coponent's variable" click="button1_clickHandler(event)"/>
<Components:MyCustomComponent myComponentVar="{myMainVar}"/>
</s:WindowedApplication>
Nested component
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[Bindable]
public var myComponentVar:String;
]]>
</fx:Script>
<s:Label text="{myComponentVar}"/>
</s:Group>
I hope it is what you're looking for :-)
来源:https://stackoverflow.com/questions/8423226/update-a-var-which-gets-it-its-value-from-another-component