Ext.onReady(function(){} )函数的作用域分析(1)
1 Ext.onReady(function(){ 2 3 var genResultDelete = function(){ 4 alert('delete') ; 5 } 6 7 var renderResult = function(value,cellmeta,record,rowIndex,columnIndex,store){ 8 var s = "<a href='#' onclick='genResultUpdate(\""+ rowIndex +"\")'>修改</a>" ; 9 s+= " <a href='javascript:genResultDelete(\""+record.data['id'] +"\")' onclick=''>删除</a>" ; 10 return s; 11 }; 12 13 14 var adviserCm = new Ext.grid.ColumnModel([ //new Ext.grid.RowNumberer(), 15 {header:'班主任编号',dataIndex:'id',sortable:false}, 16 {header:'姓名',dataIndex:'name',sortable:false}, 17 {header:'登录帐号',dataIndex:'account',sortable:false}, 18 {header:'密码',dataIndex:'password' }, 19 {header:'手机号',dataIndex:'mobile',sortable:false}, 20 {header:'email',dataIndex:'email',sortable:false}, 21 {header:'所属学科',dataIndex:'discipline.name',sortable:false}, 22 {header:'状态',dataIndex:'status',renderer:renderStatus}, 23 {header:'操作',dataIndex:'id',renderer:renderResult }
]); 26 27 28 29 var adviserStore = new Ext.data.Store({ 30 proxy:new Ext.data.HttpProxy({url:'<%=request.getContextPath()%>/system/useradviser/query.do?time=' + (new Date).getTime()}), 31 reader:new Ext.data.JsonReader({ 32 totalProperty:'totalCount', 33 root:'data' 34 },[ 35 {name:'id'}, 36 {name:'account'}, 37 {name:'discipline.id'}, 38 {name:'discipline.name'}, 39 {name:'name'}, 40 {name:'password'}, 41 {name:'mobile'}, 42 {name:'email'}, 43 {name:'status'} 44 ]), 45 remoteSort:true 46 }); 47 48 49 50 var adviserGrid = new Ext.grid.GridPanel({ 51 id:'adviser-grid', 52 title:'班主任列表', 53 store:adviserStore, 54 region:'center', 55 width:300, 56 cm:adviserCm, 57 sm: new Ext.grid.RowSelectionModel({ singleSelect: true }), 58 bbar:[ 59 new Ext.PagingToolbar( 60 { 61 pageSize:20, 62 store:adviserStore, 63 displayInfo:true, 64 displayMsg:'显示第{0}条到{1}条记录,一共{2}条', 65 emptyMsg:"没有记录" 66 })] 67 }) ; 68 69 });
上面是一个使用Extjs3.0 API写的一个班主任列表的页面的JS代码,页面效果如下:
当点击页面上的“删除”按钮时,JS会提示“缺少对象”错误(即genResultDelete 函数找不到),但如果把 Ext.onReady(function(){} ) 内部定义的
var genResultDelete = function(){
alert('delete') ;
} 改为下面方式(即去掉var关键字)就能找到genResultDelete函数
genResultDelete = function(){
alert('delete') ;
}
对于这个问题,这里先做一个简单的分析:
这是由于这个函数调用是来自Ext.onReady(function(){} )外部,也就是说点“删除”按钮时,会触发它的单击事件,此时这个调用是由dom元素发出,调用源来自于Ext.onReady(function(){} )外部,在Ext.onReady(function(){} )外部只能访问其全局变量,不能访问到Ext.onReady(function(){} )内的var方式定义的局部变量。深层次的分析将另写博客分析。