---
title: "Ext4中模型直接读取后赋值"
author: "liubl2011"
date: "2012-08-24T17:09:52Z"
tags: ["Extjs4", "model取值", "回调函数"]
categories: ["Web前端"]
slug: "ext4"
draft: false
lastmod: "2012-08-24T17:09:12Z"
id: 1662042
url: "https://liubl2011.iteye.com/blog/1662042"
---

Extjs4的model中支持数据代理proxy，在4之前的版本中数据代理只能在store里才有。现在model里有了数据代理就会更灵活的得到应用。

现在功能是直接读取后台传过来的一个bean然后给控件进行赋值。
先创建一个model：'customTarget'然后在model里面写个代理获取后台数据proxy ，然后再建立个对象customMonthTarget 用ModelManager取得model，最后在对象的load方法里获取值rec.get('launchCount');

代码如下：

```js

Ext.define('customTarget', {
    extend : 'Ext.data.Model',
    fields : [ 
        {name : 'customercount',//本月虚拟客户数
        type : 'string'
    }, {
        name : 'launchcount',//开展客户数
        type : 'string'
    } ],
    proxy : {
        type : 'ajax',
        url : basePath + 'manage/monthtarget/getCustomMonthTarget.do',
        reader : {
            type : 'json',
            root : 'customMonthTarget'
        }
    }
});

var customMonthTarget = Ext.ModelManager.getModel('customTarget');

customMonthTarget.load(1,{
     success:function(rec){
        // 本月虚拟客户数
        Ext.getCmp("customerCount").setValue(rec.get('customerCount'));

        // 开展客户数
        Ext.getCmp("launchCount").setValue(rec.get('launchCount'));
     },
     callback:function(o,response,success) {   
         if (success == false){   
             window.top.location.href = basePath + "page/errors.jsp";
         }   
     }   
 });

```


另外看load里面的callback方法，如果返回数据错误后台抛出异常情况下，在后台设置键值对success为false，在load的回调函数里写一个处理错误的连接，这样就会直接跳转的错误处理页面。我原来的想法是在spring里拦截器，如果出错spring会自动拦截跳转到另外一个页面，但是我忽略了一件事情，extjs的请求是异步的，所以拦截器无法实现错误跳转。所以只能写load的回调函数来处理了。

小宝制造。