更新:2007 年 11 月
本主題演示如何在 ASP.NET 中創(chuàng)建 AJAX 客戶端組件類。AJAX 客戶端類(包括基組件、行為和控件類)是使用原型模型和 JSON 表示法在 ECMAScript (JavaScript) 中定義的。在 JSON 表示法中,所有的原型成員都用逗號隔開。原型中的最后一個成員后面沒有逗號。
下面的示例定義一個不具有實際功能的簡單客戶端組件類。它演示如何使用原型模型來定義一個從 Component 基類派生的類。
// Declare a namespace.Type.registerNamespace("Samples");// Define a simplified component.Samples.SimpleComponent = function(){Samples.SimpleComponent.initializeBase(this);// Initialize arrays and objects in the constructor// so they are unique to each instance.// As a general guideline, define all fields here.this._arrayField = [];this._objectField = {};this._aProp = 0;}// Create protytype.Samples.SimpleComponent.prototype ={// Define set and get accessors for a property.Set_Aprop: function(aNumber){this._aProp = aNumber;},Get_Aprop: function(){return this._aProp;},// Define a method.DoSomething: function(){alert('A component method was called.');}} // End of prototype definition.// Register the class as derived from Sys.Component.Samples.SimpleComponent.registerClass('Samples.SimpleComponent', Sys.Component);
下面的步驟介紹如何定義一個 ASP.NET AJAX 客戶端類(包括控件類)。:
-
如果該類是某個命名空間的一部分,則通過調(diào)用 Type.registerNamespace 方法來注冊該命名空間。
-
在構(gòu)造函數(shù)名中定義類的構(gòu)造函數(shù)及其命名空間。在構(gòu)造函數(shù)中,聲明所有私有字段。推薦使用 this 指針將構(gòu)造函數(shù)中的私有變量聲明為實例字段。按照約定,私有字段的名稱帶有下劃線前綴。
Samples.SimpleComponent = function() { Samples.SimpleComponent.initializeBase(this); this._arrayField = []; this._objectField = {}; this._aProp = 0; }
-
定義類原型。在原型中,定義所有公共和私有方法,其中包括屬性訪問器方法和事件。
建議在構(gòu)造函數(shù)中定義所有字段。在原型中定義字段相對于在構(gòu)造函數(shù)中定義字段能夠獲得非常小的性能提升。但是,并不是所有的字段類型都可以在原型中聲明。例如,Array 和 Object 字段類型必須在構(gòu)造函數(shù)中聲明,這樣它們對于每個實例都是唯一的,而不是在原型中從所有的實例中引用。這樣可避免在針對一個實例更新組件屬性時產(chǎn)生意外結(jié)果,以致更新所有實例的值。
說明:始終通過 this 指針引用原型中的成員。使用 this 指針可以提高性能,因為工作集占用更少的內(nèi)存。
-
通過調(diào)用 Type.registerClass 方法來注冊類。有關如何使用 Type.registerClass 方法來注冊一個類并聲明該類的接口和基類的更多信息,請參見 Type.registerClass 方法。
