zoukankan      html  css  js  c++  java
  • 【翻译】EXTJS 编码风格指南与实例

    原文:EXTJS Code Style Guide with examples


    Ext JS风格指南:


    • 熟知的且易于学习
    • 快速开发,易于调试,轻松部署
    • 组织良好、可扩展和可维护


    Ext JS应用程序的命名约定:

    1、类

    类名应使用驼峰命名(CamelCased)。
    不要使用下划线,或其他连接字符。
    如:MyCustomClass

    不是通过Sencha分发的类,永远不要使用Ext作为顶层命名空间。
    在类名中,应至少使用一次点号来划分命名空间。
    如TopLevelNamespace.MyClassName

    顶层命名空间和实际类名应使用驼峰命名,而其他则应使用小写字母。
    //好的类名
    如:TopNamespace.midlevelnamespace.MyCustomClass
    如:MyModule.view.UserGrid
    //坏的类名
    eg:MyCompany.useful_util.Debug_Toolbar


    2、使用命名空间来分组相关的组件


    命名空间应基于目录结构构建。目录应基于功能化的业务组件将组件分组为逻辑模块。这意味着维护用户可根据命名空间和组件啦管理组件:

    目录结构:
    MyModule/controller/UserController.js
    MyModule/store/UserStore.js
    MyModule/model/UserModel.js
    MyModule/view/UserGrid.js
    MyModule/view/UserForm.js

    类名:
    MyModule.controller.UserController
    MyModule.store.UserStore
    MyModule.model.UserModel
    MyModule.view.UserGrid
    MyModule.view.UserForm

    3、Ext JS的组件和控件


    所有组件都应使用3个小写字母作为前缀,之后适当使用每一个单词(如txtFirstName, cboDisplay, dtmStartDate)。

    Form Panel = frm
    Text Field = txt
    Combo Box = cbo
    Button = btn
    Label = lbl
    Check Box = chk
    Date Field = dtm
    Number Field = num
    Grid = grd
    Tab Panel = tab
    Tab Page = pge
    Panel = pnl
    Container = con
    Toolbar = tlb
    Paging Toolbar = pgt

    每一个Sencha组件都应当将itemId设置为控件的名称。使用驼峰命名来为itemId命名(如txtFirstName)。
    如:itemId : txtFirstName


    4、变量、常量、私有变量、属性和方法:


    A. 变量应总是使用驼峰命名。

    如:
    var isGoodName;
    var base64Encoder;
    var thisIsMyName;
    var base64Encoder

    B. 常量应使用大写字母

    如:
     var SALARY = 1000;
     var MAX_COUNT = 10;
        var URL = "http://www.mydomain.net/";

    C. 私有变量应以“_”开始

    如: var _modelRecord;
     var _get = Ext.data.Model.prototype.get;
        var _set = Ext.data.Model.prototype.set;
        var val = _get.apply(this, arguments); // private variable used in thisway

    D. 属性应总是使用驼峰命名。静态属性应使用大写字母。

    如1:
    Ext.MessageBox.YES = "Yes";
    MyCompany.alien.Math.PI = "4.13";
    如2:
    /**@property {String} MASK_MESSAGE_SAVING_FORM Mask message for Saving form*/
        MASK_MESSAGE_SAVING_FORM: 'Saving form data, please wait...',

    E. 方法:方法应总是使用驼峰命名。这也适用于首字母缩写词。

    如:
    可接受的方法名称:
    encodeUsingMd5()
    getExtComponentByReference()
    getHtml() instead of getHTML()
    getJsonResponse() instead of getJSONResponse()
    parseXmlContent() instead of parseXMLContent()


    5. 公共基类要加注释文档

    一个组件如何被用来作为其他组件的共同祖先,它就应当被放置咋爱common目录。
    如:
    /**
     * @class Common.CommonFunctions  
     * @author Sencha User
     *  
     * 该文件包含公共功能,可被用于任何Ext JS应用程序
     *
     *
     */
    Ext.define('Common.CommonFunctions', {});


    6、为方法添加注释文档

    如:
    /**
     * This will return an ExtJs component based on a reference
     * to that component.  This reference can either be the component
     * itself or the comopnent's id.
     * @param {String/Object} ref A reference to an ExtJs component, can either be the the components id or the component itself
     * @return {Object}
     */
    function getExtComponentByReference(ref){
     var component;
     if (typeof ref === 'string'){
      component = Ext.getCmp(ref);
     } else if (typeof ref === 'object'){
      component = ref;
     } else {
      return false;
     }
     return component;
    }

    7. 为控制器的方法添加注释文档

    如:
        /**
         * Function to provide logic to validate a BPM form prior to submitting it.
         * Override this method in your own custom controller to add form specific submit validation.
         * Note:  By default this function will simply call form.isValid() to determine if form is valid.
         *
         * @returns {boolean} If the form is valid for submit or not
         */
        isBPMFormValidForSubmit: function(){
         return this.getBpmForm().isValid();
        },

    8、全局引用:

       // 注意: 要指定他们使用的地方
       var globalPreferedMode = false;
       var globalUserPreferenceArr = [];  // Array used to compare with preference cols of trade grid while applying preferences

    9、要为组件和控制器内为任何用户定义的配置项添加注释文档

    如:

    /**
      * @cfg {Number} headerColumns
      * The total number of columns to create in the table for this layout. If not specified, all Components added
      * to this layout will be rendered into a single row using one column per Component.
      */
     headerColumns: 6,
     
     /**
      * @cfg {Object/Object[]} headerFields
      * A single item, or an array of child Components to be added to this container.
      */
     headerFields: [],
     
      /** @readonly */
        isWindow: true,

       /** @cfg {String} title The default window's title */
        title: 'Title Here',

       /** @cfg {Object} bottomBar The default config for the bottom bar */
        bottomBar: {
            enabled: true,
            height: 50,
            resizable: false
        },

      /**
      * @cfg {String} store (required)
      * The key of the store to be used to back this form.
      */
     store: ''

    10、最佳实践:使用scope(作用域)

    如:

    getPeople :function(people){
     Ext.Ajax.request({
        url: 'people.php',
        method : 'GET',
        params: {
            id: 1,
            name:'test'
        },
        scope: this,
        success: this.onAfterGetPeople
     });
    },

    onAfterGetPeople:  function(response){
            //Dp some stuff
            var jsonData = Ext.decode(response.responseText);
            // process server response here
            this.getDepartments(jsonData,departments);
    },
    getDepartments : function(departments){
      Ext.Ajax.request({
          url: 'departments.php',
          method : 'GET',
          params: departments,
          scope: this,
          success: this.onAfterGetDepartments
       });
    },
    onAfterGetDepartments : function(response){
     //DO more work
    }

    11、最佳实践:正确缩进和优化代码

    如:
    segmentContactModule :function(segButton,button,pressed){

      var contactListStore = Ext.getStore('ContactListStore').
      contactView      = this.getContactView(),
      contactList      = contactView.query('#listContactItemsId')[0],
      contactDetailView= this.getContactDetailView(),
      selectedRecords  = contactList.getSelection(),
      buttonText    = button.getText();

      contactListStore.clearFilter();
     
     if(pressed) {
       if(contactListStore.getCount() == 0){
        contactDetailVIew.setActiveItem(0);
       }else{

         if(selectedRecords.length>0){
         this.contactListItemEvent(null,null,null,selectedRecords[0]);
        }else{
         contactDetailView.setActiveItem(0);
        }
       }
     }
     else{
      if(selectedRecords.lenght>0){
        this.contactListItemEvent(null,null,null,selectedRecords[0]);
      }
     }
    } // end of method

    12、最佳实践:总是让代码具有可读性


    如:
    if(!this.isReadable()){
     this.refactorWith({
      properIndentation : true,
      optimizedCodeReadability: true

      });
    }else{
     this.beHappy();
    }

    13、最佳实践:方法的返回类型

    eg:
    testSomeVal : function(someVal){
     return (someVal <=2); //添加括号提高可读性
    }

    14、最佳实践:

    延迟初始化 - 只在必要时添加条目或视图
    延迟渲染 - 节省浏览器时间
    重用某些东西 - 节省开发时间


    15、最佳实践 : 针对this的两个规则

    当一个函数通过var引用来执行时,默认的执行上下文(this)是window
    如:
    var myFn = function(){
     console.log(this);
    };
    myFn();

    当一个函数通过一个对象的键值来执行时,执行上下文(this)是object
    如:
     var member = {
      name: 'Eric',
         getName: function(){
       console.log(this);     
      }
     };
    member.getName();

    混合:
    如:
    var getName = member.getName;
    getName();

    如:
    var member1 = {
      name: 'Eric',
         getName: function(){
       console.log(this);     
      }
     };
    var member2 = {
      name: 'Bob',
         getName: member1.getName
     };
    member2.getName();


  • 相关阅读:
    SignalR了解
    轮询、长轮询、长连接、socket连接、WebSocket
    WebSocket
    FileSaver.js 实现浏览器文件导出
    上传文件调用webapi方式
    JS离开页面 弹窗
    微信公众号开发 VS2015本地调试
    C# 微信 企业号通知消息
    nginx防止DDOS攻击配置
    如何在终端使用后台运行模式启动一个Linux应用程序
  • 原文地址:https://www.cnblogs.com/hainange/p/6334149.html
Copyright © 2011-2022 走看看