EXTJS4官方文档翻译系列一:类系统和编码规范
这个方法很容易从现有的类中继承创建新的类.相比直接继承,我们没有好用的API用于类创建的其他方面,诸如:配置、静态方法、混入(Mixins)。呆会我们再来详细的重新审视这些方面。现在,让我们来看看另一个例子: 1: My.cool.Window = Ext.extend(Ext.Window, { ... });
在这个例子中,我们创建我们的新类,继承Ext.Window,放在命名空间中。我们有两个问题要解决:
第一个问题通常使用Ext.namespace(别名Ext.ns)来解决.该方法递归创建(如果该对象不存在)这些对象依赖.比较繁琐枯燥的部分是你必须在Ext.extend之前执行Ext.ns来创建它们. 1: Ext.ns('My.cool'); 2: My.cool.Window = Ext.extend(Ext.Window, { ... }); 第二个问题不好解决,因为Ext.Window可能直接或间接的依赖于许多其他的类,依赖的类可能还依赖其它类...出于这个原因,在ext4之前,我们通常引入整个ext-all.js,即使是我们只需要其中的一小部分. 1.2) 新的方式 在Extjs4中,你只需要使用一个方法就可以解决这些问题:Ext.define.以下是它的基本语法: 1: Ext.define(className, members, onClassCreated); onClassCreated: 可选的回调函数,在所有依赖都加载完毕,并且类本身建立后触发.由于类创建的新的异步特性,这个回调函数在很多情况下都很有用.这些在第四节中将进一步讨论 例如: 1: Ext.define('My.sample.Person', { 2: name: 'Unknown', 3: 4: constructor: function(name) { 5: if (name) { 6: this.name = name; 7: } 8: 9: return this; 10: }, 11: 12: eat: function(foodType) { 13: alert(this.name + " is eating: " + foodType); 14: 15: return this; 16: } 17: }); 18: 19: var aaron = Ext.create('My.sample.Person', 'Aaron'); 20: aaron.eat("Salad"); // alert("Aaron is eating: Salad"); 注意我们使用Ext.create()方法创建了My.sample.Person类的一个新实例.我们也可以使用新的关键字(new My.sample.Person())来创建.然而,建议养成始终用Ext.create来创建类示例的习惯,因为它允许你利用动态加载的优势.更多关于动态加载信息,请看入门指南:入门指南 2).配置 在ExtJS 4 ,我们引入了一个专门的配置属性,用于提供在类创建前的预处理功能.特性包括: 1: Ext.define('My.own.Window', { 2: /** @readonly */ 3: isWindow: true, 4: 5: config: { 6: title: 'Title Here', 7: 8: bottomBar: { 9: enabled: true, 10: height: 50, 11: resizable: false 12: } 13: }, 14: 15: constructor: function(config) { 16: this.initConfig(config); 17: 18: return this; 19: }, 20: 21: applyTitle: function(title) { 22: if (!Ext.isString(title) || title.length === 0) { 23: alert('Error: Title must be a valid non-empty string'); 24: } 25: else { 26: return title; 27: } 28: }, 29: 30: applyBottomBar: function(bottomBar) { 31: if (bottomBar && bottomBar.enabled) { 32: if (!this.bottomBar) { 33: return Ext.create('My.own.WindowBottomBar', bottomBar); 34: } 35: else { 36: this.bottomBar.setConfig(bottomBar); 37: } 38: } 39: } 40: }); 以下是它的用法: 1: var myWindow = Ext.create('My.own.Window', { 2: title: 'Hello World', 3: bottomBar: { 4: height: 60 5: } 6: }); 7: 8: alert(myWindow.getTitle()); // alerts "Hello World" 9: 10: myWindow.setTitle('Something New'); 11: 12: alert(myWindow.getTitle()); // alerts "Something New" 13: 14: myWindow.setTitle(null); // alerts "Error: Title must be a valid non-empty string" 15: 16: myWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100 3.Statics (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |