Ext.onReady(function(){} )函数的作用域分析(1)

时间:2022-05-05 19:39:02
 Ext.onReady(function(){

       var genResultDelete = function(){
alert('delete') ;
} var renderResult = function(value,cellmeta,record,rowIndex,columnIndex,store){
var s = "<a href='#' onclick='genResultUpdate(\""+ rowIndex +"\")'>修改</a>" ;
s+= " <a href='javascript:genResultDelete(\""+record.data['id'] +"\")' onclick=''>删除</a>" ;
return s;
}; var adviserCm = new Ext.grid.ColumnModel([ //new Ext.grid.RowNumberer(),
{header:'班主任编号',dataIndex:'id',sortable:false},
{header:'姓名',dataIndex:'name',sortable:false},
{header:'登录帐号',dataIndex:'account',sortable:false},
{header:'密码',dataIndex:'password' },
{header:'手机号',dataIndex:'mobile',sortable:false},
{header:'email',dataIndex:'email',sortable:false},
{header:'所属学科',dataIndex:'discipline.name',sortable:false},
{header:'状态',dataIndex:'status',renderer:renderStatus},
{header:'操作',dataIndex:'id',renderer:renderResult }
]); var adviserStore = new Ext.data.Store({
proxy:new Ext.data.HttpProxy({url:'<%=request.getContextPath()%>/system/useradviser/query.do?time=' + (new Date).getTime()}),
reader:new Ext.data.JsonReader({
totalProperty:'totalCount',
root:'data'
},[
{name:'id'},
{name:'account'},
{name:'discipline.id'},
{name:'discipline.name'},
{name:'name'},
{name:'password'},
{name:'mobile'},
{name:'email'},
{name:'status'}
]),
remoteSort:true
}); var adviserGrid = new Ext.grid.GridPanel({
id:'adviser-grid',
title:'班主任列表',
store:adviserStore,
region:'center',
width:300,
cm:adviserCm,
sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
bbar:[
new Ext.PagingToolbar(
{
pageSize:20,
store:adviserStore,
displayInfo:true,
displayMsg:'显示第{0}条到{1}条记录,一共{2}条',
emptyMsg:"没有记录"
})]
}) ; });

上面是一个使用Extjs3.0 API写的一个班主任列表的页面的JS代码,页面效果如下:
Ext.onReady(function(){} )函数的作用域分析(1)

当点击页面上的“删除”按钮时,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方式定义的局部变量。深层次的分析将另写博客分析。