---
title: "Extjs自定义组件"
author: "ssxxjjii"
date: "2012-11-06T16:31:44Z"
tags: []
categories: ["Web前端"]
slug: "extjs"
draft: false
lastmod: "2012-11-06T16:31:44Z"
id: 1717610
url: "https://tdcq.iteye.com/blog/1717610"
---

新件一个JS文件

 

// JavaScript Document  
Ext.namespace('CRM.Panels');  
CRM.Panels.UserDetail = Ext.extend(Ext.Panel,{  
     width:350,  
  height:120,  
  data:{  
       ID: 0,  
    FirstName: '',  
    LastName: '',  
    Email: '',  
    City: '',  
    Phone:''  
  },  
  split:true,  
  tpl: new Ext.XTemplate([  
    '&lt;div&gt;编号：{ID}&lt;/div&gt;',  
       '&lt;div&gt;姓名：{FirstName}-{LastName}&lt;/div&gt;',  
    '&lt;div&gt;电话：{Phone}&lt;/div&gt;',  
    '&lt;div&gt;城市：{City}&lt;/div&gt;',  
    '&lt;div&gt;邮箱：{Email}&lt;/div&gt;'  
  ]),  
  initComponent:function(){  
        CRM.Panels.UserDetail.superclass.initComponent.call(this);  
    if(typeof this.tpl === 'string'){  
        this.tpl = new Ext.XTemplate(this.tpl);    
    }  
    this.addEvents('UAlert');//注册新事件  
    this.addListener({//侦听函数  
         UAlert: { //注册的新事件  
       fn:this.onAlert,//调用onAlert方法   
       scope: this  
      }     
    });  
  },  
  //////////////  
  onAlert: function(){  
    alert('注册的新事件');   
  },  
  UAlert:function(){  
    this.fireEvent('UAlert');   
  },  
  /////////////////////  
  onRender: function(ct, position){  
          CRM.Panels.UserDetail.superclass.onRender.call(this, ct, position);  
    if(this.data){  
        this.update(this.data);  
    }  
  },  
  update: function(data){  
   this.data = data;  
   this.tpl.overwrite(this.body, this.data);  
  // this.fireEvent('update',this.data);  
  }  
});

//把新建的自定义组件注册为一种xtype  
Ext.reg('UserDetail',CRM.Panels.UserDetail);  
/\*使用：  
items:[  
   {  
    region:'west',  
    xtype:'UserDetail',  
    data: userData\[0],  
    title:'User Detail'  
    }      
]\*/

 

在页面上：

&lt;script language="javascript"&gt;  
 var userData = [  
    {ID:1,FirstName:'Zhang',LastName:'Jinshan',Email:'zjs@qq.com',Phone:'123456',City:'ZhangPing'},  
    {ID:2,FirstName:'Wang',LastName:'wu',Email:'wjf@qq.com',Phone:'123456',City:'ZhangPing'}  
 ];  
 Ext.onReady(function(){  
  var userDetail = new CRM.Panels.UserDetail({  
      applyTo:'body',  
   title:'User Detail',  
   data:userData\[0]  
  });  
    updateContact = function(event, el, data){  
         userDetail.update(data.data);//调用更新数据  
  }  
  Ext.get('xt').on('click',updateContact,this,{data:userData\[1]});  
  Ext.get('alert').on('click',function(){  
            userDetail.UAlert();  
            });  
 })  
&lt;/script&gt;

&lt;button id="xt"&gt;点击&lt;/button&gt;  
&lt;button id="alert"&gt;注册的新事件&lt;/button&gt;