代码改变世界

Ext.util.MixedCollection-->排序,克隆,过滤

2012-02-07 21:35    阅读(244)  评论(0)    收藏  举报

key排序和sort排序都是调用内部的_sort函数

property参数是用来判断是排序key还是value的标识

_sort : function(property, dir, fn){
        var i, len,
           
            dsc   = String(dir).toUpperCase() == 'DESC' ? -1 : 1,
            
            //弄一个数组c,以便能使用js原生的sort函数
            c     = [],
            keys  = this.keys,
            items = this.items;
        
        //默认的排序函数,很显然只能排序 asc||字符
        fn = fn || function(a, b) {
            return a - b;
        };
        
        //copy all the items into a temporary array, which we will sort
        for(i = 0, len = items.length; i < len; i++){
            //数组里的元素存放的是{},{}里复制了一套key和item和索引位置
            c[c.length] = {
                key  : keys[i], 
                value: items[i], 
                index: i
            };
        }
        
        //简单的原生数组排序
        c.sort(function(a, b){
            var v = fn(a[property], b[property]) * dsc;
            //排序的值相同,就比较索引,索引靠前的排序后的位置靠前
            if(v === 0){
                v = (a.index < b.index ? -1 : 1);
            }
            return v;
        });


浅克隆,如果复制的是对象那么复制的是引用。

clone : function(){
        var r = new Ext.util.MixedCollection();
        var k = this.keys, it = this.items;
        for(var i = 0, len = it.length; i < len; i++){
            r.add(k[i], it[i]);
        }
        r.getKey = this.getKey;
        return r;
    }

如果实现对象的深克隆,可以先Ext.encode再Ext.decode,和java的序列化反序列话实现深克隆一样道理


Ext.util.MixedCollection提供了2种过滤方式,一种是基于正则表达式的,一种是基于使用者传入的过滤函数的(这个函数需要返回boolean,true留下,false过滤掉)


基于正则表达式的

构建正则表达式的工具函数

根据传入的第一个参数(我们应该为其传入字符串),和其他配置项,构建一个正则表达式


createValueMatcher : function(value, anyMatch, caseSensitive, exactMatch) {
        if (!value.exec) { // not a regex
            var er = Ext.escapeRe;
            value = String(value);
            
           //全局匹配 
           if (anyMatch === true) {
                value = er(value);
            } else {
                value = '^' + er(value);
                //精准匹配,匹配的必定是一个单词 (^ $)开头结尾
                if (exactMatch === true) {
                    value += '

; } } //构建正则表达式 value = new RegExp(value, caseSensitive ? '' : 'i'); } return value; },


filter,filterBy返回的是一个原Ext.util.MixedCollection对象过滤后的副本