Posted on

Flex裡綁定(Bindable)相關函數及使用方式

在flex裡,最強大的標籤應該就是[Bindable]的綁定標籤了
因為某次的需求,我需要研究將Bindable綁定至函數
也順便研究了ChangeWatcher和BindingUtils的使用

【BindingUtils】
官方的說明在此:
http://help.adobe.com/zh_TW/FlashPlatform/reference/actionscript/3/mx/binding/utils/BindingUtils.html
這是Flex內綁定的工具,裡面有兩個屬性,一個是綁定到函數(bindSetter),另一個則是綁定到某物件的某屬性(bindProperty)

使用範例如下
1. 綁定到函數(bindSetter)










2. 綁定到某物件的某屬性(bindProperty)










【ChangeWatcher】
官方的說明在此:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/binding/utils/ChangeWatcher.html
因為此次我們要綁定的函數裡是有帶多個參數的,因此BindingUtils的bindSetter便無法使用
這時就需要使用BindingUtils所用的ChangeWatcher來自己做綁定的動作
ChangeWatcher的使用方式如下
var model:Model = new Model();
watcherInstance = ChangeWatcher.watch(model,[“totalItems”],itemsChanged);
根據官方文件watch的傳入的東西依序為”要綁定的物件”、”要綁定的屬性”、”要綁定的函數”

下面便是我根據這些所寫的小範例
MyBindingUtils.as
package {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.system.Capabilities;
import flash.utils.getTimer;

import mx.binding.utils.ChangeWatcher;
import mx.controls.Alert;
import mx.resources.ResourceManager;

public class MyBindingUtils extends EventDispatcher {

private static var _objs:MyBindingUtils;

public static function getInstance():MyBindingUtils {
if (_objs == null) {
_objs = new MyBindingUtils();
}
return _objs;
}

public function changeLanguage(lang:String):void {
ResourceManager.getInstance().localeChain = [lang, “en_US”];
this.dispatchEvent(new Event(“ChangeLanguage”));
}

[Bindable(event=”ChangeLanguage”)]
public function getString(type:String, key:String, parameters:Array = null, locale:String = null):String {
return ResourceManager.getInstance().getString(type, key, parameters, locale);
}

public function bindString(target:Object, prop:String, type:String, key:String, parameters:Array = null):String {
var w:ChangeWatcher = ChangeWatcher.watch(this, [“getString”], null);
var result:String = getString.apply(null, [type, key, parameters]);
if (w != null) {
var invoke:Function = function(event:*):void
{
result = getString.apply(null, [type, key, parameters]);
target[prop] = result;
};
w.setHandler(invoke);
invoke(null);
}
return result;
}
}
}

完整範例檔案可按此下載