I'm trying to create a collection class in Flex that is limited to housing a specific type of data that i am using (an interface). I have chosen not to extend the ArrayCollection class as it's too generic and doesn't really give me the compile time safety that i'm after. In it's simplistic form my collection contains an array and i manage how objects are added and removed, etc.
What i really want to be able to do is use these collections in for each loops. It definitely doesn't seem as straight forward as say c# where you just implement IEnumerable and IEnumerator (or just using the generic Collection). Is there a way to do this in action script and if so any info on how it is achieved?
Cheers
You need to extend the Flash Proxy class. Extending Proxy allows you to alter how 'get' and 'set' work, as well as 'for..in' and 'for..each' loops. You can find more details on the Livedocs.
Here's an example for your issue:
package
{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public class EnumerableColl extends Proxy
{
private var _coll:Array;
public function EnumerableColl()
{
super();
_coll = [ 'test1', 'test2', 'test3' ];
}
override flash_proxy function nextNameIndex( index:int ):int
{
if ( index >= _coll.length ) return 0;
return index + 1;
}
override flash_proxy function nextValue( index:int ):*
{
return _coll[ index - 1];
}
}
}
Take a look at Vector<>. That is about as best as you can go for a typed collection in Flex (4 onwards). However, you will need to implement your own class otherwise. One way, it seems, is to use the Iterator Pattern.
Also, take a look at this SO post.
Related
I have a quite complex validate method in module1/actions.php called from module1/executeMyAction
I would like to reuse this in module2 rather than duplicate very similar code.
It feels like I should use a component or something like this but I don't need to call validate from a template I need to call it as part of the module1/executeMyAction or module2/executeMyAction so I can then set various variables for the executeMyActionSuccess.php template to handlle.
Can anyone let me know how I should reuse this validation code, I considered moving it into the form class but that just means I can't set the template variiables and it seems like it is breaking the MVC structure a bit so I'm not happy with that.
Would really appreciate any guidance.
If you want to share some parts of code between actions you can create a custom class which will implement some methods you need. You can put the class in the lib directory of either the application or the whole project.
E.g. create a apps/frontend/lib/myUtil.class.php
class myUtil
{
public static function addNumbers($a, $b)
{
return $a + $b;
}
}
Then in your action you can just use:
$sum = myUtil::addNumbers(2, 3);
If your code depends on some other objects it's best if you don't implement static methods but create an object of the class. E.g.
class myUtil
{
protected $request;
public function __construct(sfWebRequest $request)
{
$this->request = $request;
}
public function sumFromRequest()
{
return $this->request->getParameter('a') + $this->request->getParameter('b');
}
}
then in your action
public function executeSomething(sfWebRequest $request)
{
$util = new myUtil($request);
$this->sum = $util->sumFromRequest();
}
If your code is strictly used for validation of form fields you can create a custom validator which can be then used in your form. (which will definitely be the best solution). You can read about creating custom validators in the Symfony docs.
I'm working (for my sins) on a Flex 3.3 project, which unfortunately cannot be upgraded to a newer SDK version at this stage, and have hit an issue with the custom hierarchical tree class (subclassing mx.controls.Tree) we're using. Excuse the spelling; the previous developer had a fear of dictionaries...
public class HierachyTree extends Tree
public function HierachyTree()
{
super();
iconFunction = itemIconFunc;
// etc.
}
I'm using a solution somewhere between these two methods (basically, implementing ITreeDataDescriptor) in order to add live text filtering to the component, and it's working so far:
public class HierachyTreeFilteredDataDescriptor implements ITreeDataDescriptor
{
private var filter:Function
public function HierachyTreeFilteredDataDescriptor(filterFunction:Function)
{
this.filter = filterFunction;
}
public function getChildren(node:Object, model:Object=null):ICollectionView
{
var children:ArrayCollection = new ArrayCollection([]);
// Filter the children...
return children;
}
public function hasChildren(node:Object, model:Object=null):Boolean
{
var treeItem:Object = node as Object;
if (! (treeItem is ScenarioMeta)) return (treeItem as Object).children.length > 0;
else return false;
}
The issue is that (with tree:HierachyTree) neither tree.maxVerticalScrollPosition nor the protected property tree.verticalScrollBar.maxScrollPosition updates when the search string is changed.
I've tried calling invalidateList() and invalidateDisplayList() on tree — and calling invalidateDisplayList() and invalidateSize() on tree.verticalScrollBar — to no avail.
Any ideas?
I have completely the same situation. I have a need to filter the whole tree, and I did use the solution from those 2 blogs.
Tried to validateList(), validateDisplayList(), tried to return a new collection(not filtered) on getChildren in data descriptor, but that caused other issues.
The following was the easiest and worked for me the best:
treeDataProvider.dispatchEvent(new
CollectionEvent(CollectionEvent.COLLECTION_CHANGE, false, false,
CollectionEventKind.RESET));
So, let me get this straight, what you're trying to accomplish is filter the data as per a search string inserted which should then refresh the tree?
If that's the case, it's fairly simple as long as you're using ArrayCollection as the data provider for the tree:
// Check if data is ArrayCollection
var ac:ArrayCollection;
if(tree.dataProvider is ArrayCollection)
{
ac = ArrayCollection(tree.dataProvider);
}
else if(tree.dataProvider is HierarchicalData) // Check if it's hierarchical data
{
ac = HierarchicalData(tree.dataProvider).source as ArrayCollection;
}
// filter - specify custom filter function somewhere, look at docs on how to implement
ac.filterFunction = someFilterFunction;
ac.refresh(); // Does the filtering and lets the tree know that it should redraw all nodes
I think you get the idea. Much easier to do this based on the data.
I'm using Python+PyAMF to talk back and forth with Flex clients, but I've run into a problem with the psudo-Enum-Singletons I'm using:
class Type {
public static const EMPTY:Type = new Type("empty");
public static const FULL:Type = new Type("full");
...
}
When I'm using locally created instances, everything is peachy:
if (someInstance.type == Type.EMPTY) { /* do things */ }
But, if 'someInstance' has come from the Python code, it's instance of 'type' obviously won't be either Type.EMPTY or Type.FULL.
So, what's the best way to make my code work?
Is there some way I can control AMF's deserialization, so when it loads a remote Type, the correct transformation will be called? Or should I just bite the bullet and compare Types using something other than ==? Or could I somehow trick the == type cohesion into doing what I want?
Edit: Alternately, does Flex's remoting suite provide any hooks which run after an instance has been deserialized, so I could perform a conversion then?
Random thought: Maybe you could create a member function on Type that will return the canonical version that matches it?
Something like:
class Type {
public static const EMPTY:Type = new Type("empty");
public static const FULL:Type = new Type("full");
...
// I'm assuming this is where that string passed
// in to the constructor goes, and that it's unique.
private var _typeName:String;
public function get canonical():Type {
switch(this._typeName) {
case "empty": return EMPTY;
case "full": return FULL;
/*...*/
}
}
}
As long as you know which values come from python you would just convert them initially:
var fromPython:Type = /*...*/
var t:Type = fromPython.canonical;
then use t after that.
If you can't tell when things come from python and when they're from AS3 then it would get pretty messy, but if you have an isolation layer between the AS and python code you could just make sure you do the conversion there.
It's not as clean as if you could control the deserialization, but as long as you've got a good isolation layer it should work.
I am using a Cairngorm MVC architecture for my current project.
I have several commands which use the same type of function that returns a value. I would like to have this function in one place, and reuse it, rather than duplicate the code in each command. What is the best way to do this?
Create a static class or static method in one of your Cairngorm classes.
class MyStatic
{
public static function myFunction(value:String):String
{
return "Returning " + value;
}
}
Then where you want to use your function:
import MyStatic;
var str:String = MyStatic.myFunction("test");
Another option is to create a top level function (a la "trace"). Check out this post I wrote here.
You have lots of options here -- publicly defined functions in your model or controller, such as:
var mySharedFunction:Function = function():void
{
trace("foo");
}
... static methods on new or existing classes, etc. Best practice probably depends on what the function needs to do, though. Can you elaborate?
Create an abstract base class for your commands and add your function in the protected scope. If you need to reuse it anywhere else, refactor it into a public static method on a utility class.
What I'd like to do is something like the following:
FooClass.prototype.method = function():String
{
return "Something";
}
var foo:FooClass = new FooClass();
foo.method();
Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.
The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.
Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.
Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions.
Yes, such a thing is possible.
In fact, your example is very close to the solution.
Try
foo["method"]();
instead of
foo.method();
#Theo: How would you explain the following working in 3.0.0.477 with the default flex-config.xml (<strict>true</strict>) and even a -compiler.strict parameter passed to mxmlc?
Foo.as:
package
{
public class Foo
{
public var foo:String;
public function Foo()
{
foo = "foo!";
}
}
}
footest.as:
package
{
import flash.display.Sprite;
public class footest extends Sprite
{
public function footest()
{
Foo.prototype.method = function():String
{
return "Something";
}
var foo:Foo = new Foo();
trace(foo["method"]());
}
}
}
Note that the OP said inheritance was unacceptable, as was modifying the generated code. (If that weren't the case, adding "dynamic" to the class definition would probably be the easiest solution.)
Depending on how many methods your class has, this may work:
Actual Class:
public class SampleClass
{
public function SampleClass()
{
}
public function method1():void {
Alert.show("Hi");
}
Quick Wrapper:
var actualClass:SampleClass = new SampleClass();
var QuickWrapper:Object = {
ref: actualClass,
method1: function():void {
this.ref.method1();
},
method2: function():void {
Alert.show("Hello!");
}
};
QuickWrapper.method1();
QuickWrapper.method2();
#aib is unfortunately incorrect. Assuming strict mode (the default compiler mode) it is not possible to modify the prototype of non-dynamic class types in ActionScript 3. I'm not even sure that it's possible in non-strict mode.
Is wrapping an option? Basically you create a class that takes one of the objects you get from the web service and just forwards all method calls to that, but also has methods of its own:
public class FooWrapper extends Foo {
private var wrappedFoo : Foo;
public function FooWrapper( foo : Foo ) {
wrappedFoo = foo;
}
override public function methodFromFoo( ) : void {
wrappedFoo.methodFromFoo();
}
override public function anotherMethodFromFoo( ) : void {
wrappedFoo.anotherMethodFromFoo();
}
public function newMethodNotOnFoo( ) : String {
return "Hello world!"
}
}
When you want to work with a Foo, but also have the extra method you need you wrap the Foo instance in a FooWrapper and work with that object instead.
It's not the most convenient solution, there's a lot of typing and if the generated code changes you have to change the FooWrapper class by hand, but unless you can modify the generated code either to include the method you want or to make the class dynamic I don't see how it can be done.
Another solution is to add a step to your build process that modifies the source of the generated classes. I assume that you already have a step that generates the code from a WSDL, so what you could do is to add a step after that that inserts the methods you need.
Monkey patching is an (inelegant) option.
For example, suppose you don't like the fact that Flex 3 SpriteAsset.as returns a default border metrics of [7,7,7,7] (unlike flex 2). To fix this, you can:
Create a copy of SpriteAsset.as and add it to your project at /mx/core/SpriteAsset.as
Edit your local copy to fix any problems you find
Run your ap
Google "flex monkey patch" for more examples and instructions.