Dev.Hong
将欲取之 必先予之……
随笔- 53  文章- 0  评论- 220 
博客园  首页  新随笔  联系  管理  订阅 订阅
Js模仿属性和委托

属性
 1 //定义一个用于模仿C#中的属性对象
 2 Property = Class.create();
 
3 Property.prototype = {
 
4     initialize : function(){
 
5         var arr = arguments;
 
6         this._getfunction = arr[0] ? arr[0] : null;
 
7         this._setfunction = arr[1] ? arr[1] : null;
 
8         arr = null;
 
9     },
10     get : function(){
11         if ( this._getfunction != null )
12             return this._getfunction.apply( this, arguments );
13         return null;
14     },
15     set : function(){
16         if ( this._setfunction != null )
17             this._setfunction.apply( this, arguments );
18     },
19     dispose : function(){
20         this._getfunction = null;
21         this._setfunction = null;
22     }
23 }

下面是使用实例
 1     //扩展 Object 属性 Size
 2     Object.Size = new Property( function(){
 
3                                     //此处为你的 Get 方法实现
 4                                 }.bind( this ),
 
5                                 function(){
 
6                                     //此处为你的 Set 方法实现
 7                                 }.bind( this ) );
 
8     //使用方法
 9     alert( Object.Size.get() );
10     Object.Size.set( { width : 100, height : 200 } );
11 

委托
 1 //定义一个用于模仿C#中委托对象
 2 Delegate = Class.create();
 
3 Delegate.prototype = {
 
4     initialize : function(){
 
5         this._InvocationList = null;
 
6     },
 
7     addHandler : function( del ){
 
8         this.getInvocationList().add( del );
 
9     },
10     removeHandler : function( del ){
11         this.getInvocationList().remove( del );
12     },
13     getInvocationList : function(){
14         if ( this._InvocationList == null )
15             this._InvocationList = new Array();
16             
17         return this._InvocationList;
18     },
19     invoke : function(){
20         var par = arguments;
21         this.getInvocationList().each( function( item ){
22             item.apply( this, par );
23         });
24     },
25     dispose : function(){
26         if ( this._InvocationList != null ){
27             this._InvocationList.clear();
28             this._InvocationList = null;
29         }
30     }
31 }

应用如下
 1     //声明一个委托
 2     Object.Disposed = new Delegate();
 
3     //订阅一个委托
 4     Object.Disposed.addHandler( function(){
 
5                                     //此处为你的实现
 6                                 }.bind( this ) );
 
7     //引发 Disposed 事件
 8     Object.__onDisposed = function(){
 
9         if ( this.Disposed && this.Disposed != null ){
10             this.Disposed.invoke();//可以传参数,也可无
11         }
12     }


以上代码中用到了 Prototype.js 框架
posted on 2007-04-12 16:00 Dev.Hong 阅读(268) 评论(0) 编辑 收藏
刷新评论刷新页面返回顶部
程序员问答社区,解决您的IT难题
博客园首页博问新闻闪存程序员招聘知识库
Copyright ©2012 Dev.Hong