How to use an external actionscript file with flex - actionscript-3

I'm building a Flash 4 Builder project and want to use an external actionscript file. Here is the structure I used...
http://img704.imageshack.us/img704/794/schermafbeelding2010121b.png
So, I want to be able to connect "actionscript.as" to the "OrderApp.mxml" file.
I add this <fx:Script source="assets/actionscript/actionscript.as"/> to my OrderAp.mxml file and a function in actionscript.as looks for example like this:
public function checkCode():void{
if (txtToegangscode.text == "moia") {
lblFeedback.text = "ok";
txtToegangscode.enabled = false;
btnGaNaarPersonen.visible = true;
btnGaVerder.visible = false;
} else {
lblFeedback.text = "wrong";
}
}
When I want to add some components, like "Toegangscode.mxml" I keep getting errors like "1120: Acces of undefined property lblFeedback". When I try to call the function checkCode() What do I do wrong?

You probably already found the answer you were looking for, however, there is this link to Adobe's site that has all the info you or other readers need.
http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf61c8a-7ff4.html

Problem solved... Apparently, you have to use a different .as file for every component! Nevertheless thanks to everyone who helped me out!

Looks like you are missing the double quote at the start of the string?
lblFeedback.text = wrong";
should be...
lblFeedback.text = "wrong";
Why not put this code into a class then you can detect any compile errors?

EDITED:
Sorry I did not look carefully at your question.
Your problem is that the *.as file does not know what your components are:
You need to pass the components to the function like so:
public function checkCode(txtToegangscode:TextInput, lblFeedback:Label):void{
if (txtToegangscode.text == "moia") {
lblFeedback.text = "ok";
txtToegangscode.enabled = false;
btnGaNaarPersonen.visible = true;
btnGaVerder.visible = false;
} else {
lblFeedback.text = "wrong";
}
This will allow your *.as file to access the properties in those components.
OLD:
Here is the documentation: http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_4.html
You use the source attribute of the tag to include external ActionScript files in your Flex applications. This provides a way to make your MXML files less cluttered and promotes code reuse across different applications.
Do not give the script file the same name as the application file. This causes a compiler error.
The following example shows the contents of the IncludedFile.as file:
// usingas/includes/IncludedFile.as
public function computeSum(a:Number, b:Number):Number {
return a + b;
}
The following example imports the contents of the IncludedFile.as file. This file is located in the includes subdirectory.
<?xml version="1.0"?>
<!-- usingas/SourceInclude.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script source="includes/IncludedFile.as"/>
<mx:TextInput id="ta1st" text="3" width="40" x="170" y="24" textAlign="right"/>
<mx:TextInput id="ta2nd" text="3" width="40" x="170" y="52" textAlign="right"/>
<mx:TextArea id="taMain" height="25" width="78" x="132" y="82" textAlign="right"/>
<mx:Button id="b1" label="Compute Sum"
click="taMain.text=String(computeSum(Number(ta1st.text), Number(ta2nd.text)));"
x="105"
y="115"
/>
<mx:Label x="148" y="52" text="+" fontWeight="bold" fontSize="17" width="23"/>
</mx:Application>
The source attribute of the tag supports both relative and absolute paths.
The source attribute of the tag and the include directive refer to files in different ways.
The following are the valid paths to external files that are referenced in an tag's source attribute:
Relative URLs, such as ../myscript.as. A relative URL that does not start with a slash is resolved relative to the file that uses it. If the tag is included in "mysite/myfiles/myapp.mxml," the system searches for "mysite/IncludedFile.as".
For an ActionScript include directive, you can reference only relative URLs. Flex searches the source path for imported classes and packages. Flex does not search the source path for files that are included using the include directive or the source attribute of the tag.

Related

TVML Add items dynamically?

I have seen this question (Force view to reload tvml content on Apple TV/tvos) and the answer describes how you could remove things from the DOM but is there any way to add them?
I know about the standard appendChild on a NodeList but how would you create the proper element to be appended? That is, when you create a document in TVML it is a special XML syntax that is then parsed into a document. Is there a way to parse just a portion of a document so that you can then add it into, say a section within a shelf to dynamically add more items to the row after the document has been presented?
P.S. I've tried using Presenter.parser.parseFromString() with the xml for the new item but it is throwing a IKDOMException with that syntax.
There are many approaches you can take to accomplish adding items dynamically. An important thing to note is that Apple's sample code is NOT structured for dynamic data very well.
After you create a template, you can change the document in a variety of ways. You should have ownership of the document after the template is created. In the following example, the variable doc contains a Stack Template document I'd like to manipulate.
var shelves = doc.getElementsByTagName("shelf"); //get all the shelves
var shelfToAddTo = shelves.item(0); //choose the index for the shelf you want to add to.
var sectionToAdd = `<section>
<lockup>
<img src="pathToImg" width="100" height="100"/>
<title>Title Goes Here</title>
</lockup>
</section>`;
shelfToAddTo.insertAdjacentHTML('beforeend', sectionToAdd); //this will add the new section before the </shelf> tag.
This will add a new section and lockup to the first shelf in your document.
UPDATE:
You can use DataItem API to manage your data with prototypes.
You can’t bind JSON objects directly to a template, you have to turn them into DataItem objects. Retrieve the desired section element and create a new data item for the section. Create new data items from the JSON objects. The setPropertyPath method is used bind the new data items to the section data item. Listing 5-4 shows a modified parseJson function that takes the information from the Images.json file, turns them into data items, and binds them to the appropriate section.
Using the prototype element, you can create a single lockup that contains like objects. Inside of the lockup, you define the structure of the lockup. Listing 5-5 shows a lockup that displays the objects defined as artwork in the type element. The URL and title for each image are pulled from the JSON object.
<prototypes>
<lockup prototype="artwork">
<img binding="#src:{url};" width="200" height="300"/>
<title binding="textContent:{title};" />
</lockup>
</prototypes>
<section binding="items:{images};" />
The following iterate and populate your prototype code using items from section:
function parseJson(information) {
var results = JSON.parse(information);
let parsedTemplate = templateDocument()
navigationDocument.pushDocument(parsedTemplate)
let shelf = parsedTemplate.getElementsByTagName("shelf").item(0)
let section = shelf.getElementsByTagName("section").item(0)
//create an empty data item for the section
section.dataItem = new DataItem()
//create data items from objects
let newItems = results.map((result) => {
let objectItem = new DataItem(result.type, result.ID);
objectItem.url = result.url;
objectItem.title = result.title;
return objectItem;
});
//add the data items to the section's data item; 'images' relates to the binding name in the protoype where items:{images} is all of the newItems being added to the sections' data item;
section.dataItem.setPropertyPath("images", newItems)
}
Template:
<document>
<stackTemplate>
<banner>
<title>JSON Shelf</title>
</banner>
<collectionList>
<shelf>
<prototypes>
<lockup prototype="artwork">
<img binding="#src:{url};" width="200" height="300"/>
<title binding="textContent:{title};" />
</lockup>
</prototypes>
<section binding="items:{images};" />
</shelf>
</collectionList>
</stackTemplate>
</document>
Reference:
https://developer.apple.com/library/content/documentation/TVMLKitJS/Conceptual/TVMLProgrammingGuide/GeneratingContentForYourApp.html
Hope it helps you.

Dynamic XML Template in TVML/TVJS

Does anyone know how to Dynamically generate a template in an apple tv app using TVJS/TVML? Basically I want to hit my API, get back an array of objects and then insert that data into my XML template.
I've been searching for info on how to accomplish it but have come up short. I've found many tutorials that use hard coded images, videos, etc but nothing dynamically generated.
Any help would be appreciated.
Finally, I've figured this out. It wouldn't be difficult to generate a template on-the-fly, but instead I wanted to reuse the Presenter and the ResourceLoader, and to have the template as a *.xml.js file. Here is the solution I managed to arrive at.
For the initial view, I used a catalogTemplate, as demonstrated in Ray Wenderlich's tutorial. Instead of conference talks, however, I was displaying categories of men's and women's merchandise. Once a category was selected, I wanted to display a stackTemplate with a number of options for that category. The problem was how to pass any information, the title of the category in the simplest case, to the second template.
In the first template, I had the lockups configured like so:
<lockup categoryTitle="Women: Dresses" categoryDir="w-dresses">
<img src="${this.BASEURL}images/dresses.jpg" width="230" height="288" />
<title>Dresses</title>
</lockup>
In application.js, I had a listener attached, in the same way how tutorials show:
doc.addEventListener("select", Presenter.load.bind(Presenter));
Here is the second template (Category.xml.js):
var Template = function(categoryTitle) {
return `<?xml version="1.0" encoding="UTF-8" ?>
<document>
<stackTemplate>
<banner>
<title>${categoryTitle}</title>
</banner>
</stackTemplate>
</document>`
}
This is a JavaScript, so in your case you can pass into the function, say, an array of values and then construct the template accordingly. The tricky part was to pass a value.
First, I made a couple of changes to the ResourceLoader (this can be done better, of course, it's just a proof of concept). I simply added categoryTitle as an additional parameter to the top-level function and when calling the Template:
ResourceLoader.prototype.loadResource = function(resource, callback, categoryTitle) {
var self = this;
evaluateScripts([resource], function(success) {
if(success) {
var resource = Template.call(self, categoryTitle);
callback.call(self, resource);
} else {
var title = "Resource Loader Error",
description = `Error loading resource '${resource}'. \n\n Try again later.`,
alert = createAlert(title, description);
navigationDocument.presentModal(alert);
}
});
}
Finally, in the Presenter, in the load, I am passing categoryTitle to the resourceLoader:
load: function(event) {
var self = this,
ele = event.target,
categoryTitle = ele.getAttribute("categoryTitle");
if (categoryTitle) {
resourceLoader.loadResource(`${baseURL}templates/Category.xml.js`, function(resource) {
var doc = self.makeDocument(resource);
self.pushDocument(doc);
}, categoryTitle);
}
},
This works for me.
One final note: for some categories, I had titles with an ampersand, like 'Tops & T-shirts'. Naturally, I replaced the ampersand with an XML entity: 'Tops & T-shirts'. This, however, didn't work, probably because this string was decoded twice: the first time the entity was turned into an ampersand, and on the second pass the single ampersand was flagged as an error. What worked for me was this: 'Tops &amp; T-shirts'!
It is simple if you are using atvjs.
// create your dynamic page
ATV.Page.create({
name: 'homepage',
url: 'path/to/your/json/data',
template: function(data) {
// your dynamic template
return `<document>
<alertTemplate>
<title>${data.title}</title>
<description>${data.description}</description>
</alertTemplate>
</document>`;
}
});
// later in your app you can navigate to your page by calling
ATV.Navigation.navigate('homepage');
Disclaimer: I am the creator and maintainer of atvjs and as of writing this answer, it is the only JavaScript framework available for Apple TV development using TVML and TVJS. Hence I could provide references only from this framework. The answer should not be mistaken as a biased opinion.
I'm using PHP to generate the TVML files dynamically, configuring the output as text/javascript format:
<?php
header("Content-type: application/x-javascript");
[run your PHP API calls here]
$template = '<?xml version="1.0" encoding="UTF-8" ?>
<document>
... [use PHP variables here] ...
</document>';
echo "var Template = function() { return `". $template . "`}";
?>
You can dynamically generate a template by creating a dynamic string that represents the xml in a TVML template.
Review the code in here: https://developer.apple.com/library/prerelease/tvos/samplecode/TVMLCatalog/Listings/client_js_Presenter_js.html#//apple_ref/doc/uid/TP40016505-client_js_Presenter_js-DontLinkElementID_6
This file has functions that can be used to create an XML document that can represent a view.
You can make an XMLHttpRequest (ex: consuming API JSon calls through TVJS-tvOS) bring back some JSON data and then dynamically generate an XML document that conforms to one of the TVML templates. Parse it into an XML document and then navigate to the document.

Word having single quotes search from xml file using jquery issue

Hi I need to parse XML file using jquery. I created read and display functionality. But when a word having single quote not working.
My XML is like this
<container>
<data name="Google" definition="A search engine"/>
<data name=" Mozilla's " definition="A web browser"/>
</ container>
using my jquery code I can read definition of Google. But I can't read Mozilla's definition due to that single quotes. This is my jquery code.
var displayDefinition = function(obj){
$.get("definitions.xml", function(data){
xml_data1.find("data[name^='"+obj.innerHTML+"']").each(function(k, v){
right=''+ $(this).attr("Defination") + '';
}
}
$(".result").append(right);
}
Any body knows the solution for this please help me.
Thanks
jQuery deals with single quotes very well. the structure of your function looks really wild though. I changed it a big assuming you want to create a function that can display the definition based on passing it a name: http://jsfiddle.net/rkw79/VQxZ2/
function display(id) {
$('container').find('data[name="' +id.trim()+ '"]').each(function() {
var right = $(this).attr("definition");
$(".result").html(right);
});
}
Note, you have to make sure your 'name' attribute does not begin or end with spaces; and just trim the string that the user passes in.

as3 namespace - get an attribute with a minus sign in it [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
e4x / as3: How to access a node with a dash in its name.
I've set the namespace for my XML to use SMIL and I'm able to pull the src attribute of an element this way:
my.node.#src which gets "this is some URL"
However, I have another attr called 'system-bitrate'. Because of the minus sign, I can't do #system-bitrate So I attempted what I normally do which is my.node.attribute('system-bitrate') which isn't working.
Oddly enough, not even my.node.attribute('src') works. I suspect this is due to the namespace? So how to I get attributes out using ny.node.attribute ?
The only thing that works is my.node.attributes()[1]. I know that's not the "right way" so I'm hoping someone can enlighten me!
FYI I'm working with SMIL files
** edit **
Here's the namespace required for the XML I'm using:
default xml namespace = new Namespace('http://www.w3.org/2001/SMIL20/Language');
And an example of the XML I'm working with:
<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
<head>
<meta name="title" content="Live"/>
</head>
<body>
<switch>
<video src="myStreamName" system-bitrate="200000"/>
</switch>
</body>
</smil>
** code sample for DennisJaaman **
default xml namespace = new Namespace('http://www.w3.org/2001/SMIL20/Language');
var xml:XML = XML(event.target.data);
for each(var o:XML in xml.body['switch'].video) {
if(!hs) hs = o;
else {
trace(o.attributes()[1]); // works
trace(o.#url); // doesn't work either (makes me wonder about NS issues
trace(o['#system-bitrate']); // doesn't work
trace(o.attribute('#system-bitrate') // doesn't work
// etc etc, I just left a few in here
}
}
Try to use square brackets like in the sample below:
default xml namespace = new Namespace("http://www.w3.org/2001/SMIL20/Language");
var xmlSmpl:XML=<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
<head>
<meta name="title" content="Live"/>
</head>
<body>
<switch>
<video src="myStreamName" system-bitrate="200000"/>
</switch>
</body>
</smil>;
trace (xmlSmpl.body['switch']['video']['#system-bitrate']);
Behold! The power of QName!
my.node.attribute(
new QName( 'http://www.w3.org/2001/SMIL20/Language', 'system-bitrate' )
)
The thing about attribute (and descendant, and child...) is that its parameter is type * (anonymously). This is because it really isn't a String, it is coerced to a QName (without a URI) in the background. This means you were searching under the default URI for something under the URI above.
Let me know how that code above works out.
Check out this post:
e4x / as3: How to access a node with a dash in its name
******EDIT****:
And use the following notation to get XML Attributes that contain a - (dash)
trace("Video system-bitrate: " + my.node.video["#system-bitrate"]);
These do not work:
trace("Video system-bitrate: " + my.node.video.#["system-bitrate"]);
trace("Video system-bitrate: " + my.node.video.attribute("#system-bitrate"));
For more info check the LiveDocs
Cheers

Accessing properties via a String in AS3

I have an engine I created a while back that loads objects into a container based on XML data. A really quick example of the XML would be like this:
<level>
<object cname="enemies.Robot">
<pos x="200" y="400" layer="mobiles" />
</object>
<object cname="Player">
<pos x="12" y="89" layer="mobiles" />
</object>
</level>
I have a class Environment that has a method loadLevel(data:XML) which I parse the XML through, then the function runs through the XML finding all object nodes and uses getDefinitionByName to determine which Object I want to create based on object.#cname.
From here, I have to manually define each property based on the XML like so;
obj.x = xml.pos.#x;
obj.y = xml.pos.#y;
etc.
I was wondering if there's an inbuilt method for setting a property based on a String. By this I mean something like so:
var mc:MovieClip = new MovieClip();
mc.someInbuiltFunctionThatSetsAProperty("alpha", 0.5);
This way I could change my XML to be more like so:
<object cname="Player">
<props>
<x>200</x>
<y>221</y>
<alpha>7834</alpha>
<health>Something</health>
<power>3</power>
</props>
</object>
And iterate through all the children of props to set all of my properties on the fly.
I know if I create an Object and set properties within it like so:
var obj:Object =
{
var1: "hello",
var2: "there",
name: "marty"
};
That you can then iterate through names/values using the for(String in Object) loop like this:
var i:String;
for(i in obj)
{
trace(i + ": " + obj[i]);
}
/**
* Output:
* var1: hello
* var2: there
* name: marty
*/
Is there maybe something even similar to that?
Surely there's a way, as here's an example of identifying a property using a String:
var ar:Array = [new MovieClip(), new MovieClip()];
ar.sortOn("alpha", Array.ASCENDING);
So just to make my question more to-the-point: I want to be able to get and set properties that I can identify using a String.
Why not using ["string property"] notation :
var mc:MovieClip=new MovieClip()
mc["alpha"] = 0.5 // setter
var alpha:Number=mc["alpha"] // getter
I'm not quite clear on what it is you're looking for exactly, but I have a general sense of what you're getting at and have a few suggestions for you. First, have a look at the documentation for the Object class in the AS3 Language Reference. Look specifically at the propertyIsEnumerable() and setPropertyIsEnumerable() methods. I think that's what you're asking about.
If not, you might want to look into the behavior of dynamic classes, which let you add variables to an object on the fly.