How can I bind variables in a AS3 Flash Project?
I'd appreciate if you could link me to an example of how to bind two variables in AS3, but for a Flash project instead of a Flex project. I found references to binding with Flex, but I assume this should be somehow possible in Flash as well.
Let me explain using the following example:
every time I change foo somewhere in the code, I want bar to change to the same value.
public class bindable_variables{
var foo: String;
var bar: String开发者_运维百科;
public function bindable_variables()
{
//bind foo to bar so every change to foo affect bar
}
}
Thanks.
P.S. I found this post, but couldn't figure out how to use it. How do I use Flex's Binding in a Flash AS3 project
BindingUtils
is a class in the Flex SDK, which is why the other post you linked to isn't applicable in your case.
To achieve binding without accessing the Flex libraries, you'll have to manually write event dispatchers and corresponding handlers.
The following article might be helpful in getting you started, since it has both Flash-only and Flex code: Introduction to Event Handling in AS3
There might be better ways of doing it, but, in essence, you need to wrap any variable that you want to bind to in a class that extends EventDispatcher. For example, something like:
public class BindableString extends EventDispatcher {
private var _value:String = '';
public function BindableString(str:String = null) {
value = str;
}
public function set value(str:String):void {
_value = str;
dispatchEvent(new Event(Event.CHANGE));
}
public function get value():String {
return _value;
}
}
Then, in some other class you'll need a handler, eg.:
public class MyClass {
public var foo:BindableString = new BindableString();
private var _bar:String = "bar";
public function MyClass() {
foo.addEventListener(Event.CHANGE, handleFooChange);
foo.value = "foo";
trace(_bar); // "foo"
}
private function handleFooChange(e:):void {
_bar = foo.value;
}
}
Then every change in foo
should get propagated to _bar
.
That's the basic outline. I didn't run this code, but it should provide a basis to accomplish the binding. This should also allow you to bind to foo
outside of MyClass
.
Maybe someone else might know if there might already be a good descendant of EventDispatcher, which might already implement this functionality. I'm primarily a Flex coder, so I don't know of any off the top of my head.
You could achieve the same by using getters and setters.
public class bindable_variables{
private var _foo: String;
public var bar: String;
public function bindable_variables()
{
foo = "a string";
trace("bar: " + bar);
}
public function set foo(newFoo:String):void
{
_foo = newFoo;
bar = foo;
}
public function get foo():String
{
return _foo;
}
}
精彩评论