Ext数据组件之Store,Model

版本:5.1.0

说在前面:多个Model通常和一个Store配合使用。Store是多个record的集合(record是model的实例)。

举个例子:Store最终是要服务于Ext的组件的,就比如多选框(combobox)和网格(grid)。那么,store是怎么给组件提供服务的呢,见代码:

1. combobox:

    'use strict';


    Ext.onReady(function(){

        var states = Ext.create('Ext.data.Store', {
            fields: [//要注意的是,Store的会根据fields里的元素自动创建Model。
                    //fields可以为空,Ext会根据数据的字段名,自行创建model
            //要是创建Store没有加fields属性,会有Ext.data.Store created with no model.的警告
// 'abbr', 'name' ], data : [//准备的内联数据,可以内联,也可以请求获取,这里只做一个例子。 {"abbr":"AL", "name":"Alabama"}, {"abbr":"AK", "name":"Alaska"}, {"abbr":"AZ", "name":"Arizona"} //... ] }); //上方的Store会根据fields创建一个类似这样的model Ext.define('MyComboModel', { extend: 'Ext.data.Model', fields: [ //fields可以为空,但实例化的时候要写明 // {name: 'abbr', type: 'string'}, // {name: 'name', type: 'string'} ] }); Ext.create('Ext.window.Window', { title: 'Hello', height: 200, width: 400, layout: 'fit', items:[ { xtype:'form', items:[ { xtype:'combobox', fieldLabel: 'Choose State', store: states, queryMode: 'local', displayField: 'name', valueField: 'abbr', id:'mycombo' },{ xtype:'button', text:'点击', handler:function(){ console.log('nmsl'); // var curType = Ext.create('MyComboModel', { // abbr : 'CS', // name:'长沙' // });
//

                   //实例化model    var curType = new MyComboModel({ 'abbr':'CS', 'name':'长沙' }); // Ext.getCmp('button'). Ext.getCmp('mycombo').setSelection(curType); } } ] } ] }).show(); });

 

2.grid

 这个表格,从后台发ajax异步取数据,然后数据通过store的proxy来加载和存储数据。

    'use strict';

    Ext.onReady(function(){
        

        
        var gridStore = Ext.create('Ext.data.Store', {
            fields:[]
            //这里并没有定义proxy,但是ext会默认定义一个type为‘memory’的proxy
        });
        
        

        //如果proxy的type为ajax,依旧可以使用gridStore.setData()方法来赋值
        /*
        var gridStore = Ext.create('Ext.data.Store', {
            
            fields:[],
            proxy : {
                type: 'ajax',
                url: '/play/diana',
                reader :{
                    type : 'json',
                }
            },
            autoLoad: true
        });
        */
        
        
        //var lemGrid;
        var lemGrid = Ext.create('Ext.grid.Panel',{
            title:'账户表',
            store:gridStore,
            columns: [
                      { text: 'one', dataIndex: 'PARAID' },
                      { text: 'two', dataIndex: 'PANAME', flex: 1 },
                      { text: 'three', dataIndex: 'PAPAID' },
                      { text: 'four', dataIndex: 'PARAAA' },
                      { text: 'five', dataIndex: 'KEYVAU' }
                  ]
        });
        
        
        Ext.create('Ext.container.Viewport', {
            layout: 'border',
            items: [{
                region: 'north',
                html: '<h1 class="x-panel-header">Diana\'s Space</h1>',
                border: false,
                margin: '0 0 5 0'
            }, {
                region: 'west',
                collapsible: true,
                title: 'Navigation',
                width: 150
                // could use a TreePanel or AccordionLayout for navigational items
            }, {
                region: 'south',
                title: 'South Panel',
                collapsible: true,
                html: 'Information goes here',
                split: true,
                height: 100,
                minHeight: 100
            }, {
                region: 'east',
                title: 'East Panel',
                collapsible: true,
                split: true,
                width: 150
            }, {
                region: 'center',
                xtype: 'tabpanel', // TabPanel itself has no title
                activeTab: 0,      // First tab active by default
                items: [
                    lemGrid
                ]
            }]
        });
        
        
        //也可使用proxy自带的异步方法来请求数据,见以上proxy的type属性为'ajax'的那段代码。
        _.ajax({
            success:function(res){
                //请求的数据,赋予给store
                gridStore.setData( JSON.parse(res.responseText) );
            },
            method:'get',
            url:'diana'
        });
        
        
    });

为了不增加学习成本引入新的框架, 在以上代码中使用的_.ajax方法为自编的方法,实现方法如下:

(function(){


    var root = this;
    
    
    var _ = function (obj) {
        if (obj instanceof _) {
            console.log('= =');
            return obj;
        }
        console.log('1');
        if (!(this instanceof _)) return new _(obj);
        console.log('2');
        this._wrapped = obj;
    };


    // 把underscore对象暴露到全局作用域
    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
          exports = module.exports = _;
        }
        exports._ = _;
    } else {
        root._ = _;
    }

    
    _.ajax = function(options){

        var xhr = createXHR();
        
        xhr.onreadystatechange =  function(){
            if(xhr.readyState === 4){
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ //success
                    
                    options.success(xhr);
                                
                } else { 
                    console.log("Request was unsuccessful: " + xhr.status); 
                }
            }
        };
        
        xhr.open(options.method,options.url,true);  //第三个参数 ,是否异步
        xhr.send(null);


    };

    function createXHR(){
        if (typeof XMLHttpRequest != "undefined"){ 
            return new XMLHttpRequest();
        } else if (typeof ActiveXObject != "undefined"){ 
            if (typeof arguments.callee.activeXString != "string"){ 
                var versions = [ "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"],
                i, len;

                for (i=0,len=versions.length; i < len; i++){ 
                    try { 
                        new ActiveXObject(versions[i]);
                        arguments.callee.activeXString = versions[i]; 
                        break;
                    } catch (ex){ 
                    //跳过
                    } 
                } 
            } 

            return new ActiveXObject(arguments.callee.activeXString); 
            
        } else {
            throw new Error("No XHR object available.");
        } 
    }

})()

 

posted @ 2019-08-26 01:38  lee_oy  阅读(638)  评论(0编辑  收藏  举报