AS3中类似watch的功能

作者:袖梨 2022-07-02

/**
*
* @class:WO(.watch)
* @author:ycccc8202
* @date:2007.8.2
* @example:
* import com.ycccc.utils.WO;
* var mc:MovieClip=new MovieClip();
* var __mc:WO=new WO(mc);
* var arg:String="1234";
* __mc.watch("x",watchFunc);
* function watchFunc(p,o,n,a) {
* trace(arguments);
* return n;
* }
* __mc.x=99;
* __mc.x=100;
* __mc.watch("y",watchFunc,arg);
* __mc.y=101;
* __mc.y=102;
*
**/
package com.ycccc.utils{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class WO extends Proxy {;
private var _obj:*;
private var _watchHashTable:Object;
/**Constructor WO
*
* @param obj:* 对象
*
**/
public function WO(obj:*) {
  _watchHashTable={};
  _obj=obj;
}
/**Public function watch
*
* @param prop:String 属性
* @param callBackFunc:Function 回调函数
* @param arg:*=null 可选参数
*
**/
public function watch(prop:String,callBackFunc:Function,arg:*=null):void {
  _watchHashTable[prop]={};
  _watchHashTable[prop].prop=prop;
  _watchHashTable[prop].oldV=flash_proxy::getProperty(prop);
  _watchHashTable[prop].newV=null;
  _watchHashTable[prop].callBackFunc=callBackFunc;
  _watchHashTable[prop].arg=arg;
}
override flash_proxy function callProperty(methodName:*, ... args):* {
  return _obj[methodName].apply(_obj,args);
}
override flash_proxy function getProperty(name:*):* {
  //trace("getProperty");
  return _obj[name];
}
override flash_proxy function setProperty(name:*, value:*):void {
  //trace("setProperty");
  if (_watchHashTable[name]!=undefined && value!=_watchHashTable[name].oldV) {
   _watchHashTable[name].newV=value;
   _watchHashTable[name].oldV=_watchHashTable[name].callBackFunc.apply(null,[_watchHashTable[name].prop,_watchHashTable[name].oldV,_watchHashTable[name].newV,_watchHashTable[name].arg]);
  }
  _obj[name] = value;
}
}
}

import com.ycccc.utils.WO;
var mc:MovieClip=new MovieClip();
var __mc:WO=new WO(mc);
var arg:String="1234";
__mc.watch("x",watchFunc);
function watchFunc(p,o,n,arg) {
trace(arguments);
return n;
}
__mc.x=99;
__mc.x=100;
__mc.watch("y",watchFunc,arg);
__mc.y=101;
__mc.y=102;
__mc.watch("z",watchFunc,arg);
__mc.z=88
__mc.z=99

相关文章

精彩推荐