`
apache
  • 浏览: 6361 次
社区版块
存档分类
最新评论

ext mon 和 on 的区别

阅读更多
mon和on方法都是给对象添加事件句柄的方法:
1.on方法实际上addListener的简写, 是在Ext.util.Observable中定义的,其作用是
"Appends an event handler to this object.",也就是给当前对象添加事件处理函数
代码如下(没太看懂) 是个递归的函数
        addListener : function(eventName, fn, scope, o){
            var me = this,
                e,
                oe,
                isF,
            ce;
            if (ISOBJECT(eventName)) {
                o = eventName;
                for (e in o){
                    oe = o[e];
                    if (!filterOptRe.test(e)) {
                        me.addListener(e, oe.fn || oe, oe.scope || o.scope, oe.fn ? oe : o);
                    }
                }
            } else {
                eventName = toLower(eventName);
                ce = me.events[eventName] || TRUE;
                if (typeof ce == "boolean") {
                    me.events[eventName] = ce = new EXTUTIL.Event(me, eventName);
                }
                ce.addListener(fn, scope, ISOBJECT(o) ? o : {});
            }
        },


2. mon方法是在Ext3为了解决内存泄漏问题(啥问题不知道,应该是部分句柄可能存在无法自动删除的情况)作出的改进,定义于Component类, 可以在当前对象内添加在外部对象的事件句柄, 在当前对象销毁的时候会自动清除句柄。代码如下:
    mon : function(item, ename, fn, scope, opt){
        if(!this.mons){
            this.mons = [];
            this.on('beforedestroy', this.clearMons, this, {single: true});
        }

        if(Ext.isObject(ename)){
        	var propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;

            var o = ename;
            for(var e in o){
                if(propRe.test(e)){
                    continue;
                }
                if(Ext.isFunction(o[e])){
                    // shared options
			        this.mons.push({
			            item: item, ename: e, fn: o[e], scope: o.scope
			        });
			        item.on(e, o[e], o.scope, o);
                }else{
                    // individual options
			        this.mons.push({
			            item: item, ename: e, fn: o[e], scope: o.scope
			        });
			        item.on(e, o[e]);
                }
            }
            return;
        }


        this.mons.push({
            item: item, ename: ename, fn: fn, scope: scope
        });
        item.on(ename, fn, scope, opt);
    },

从代码中,很清楚的看到当前对象在模板方法beforedestroy中会自动的进行句柄清理工作,减少了内存泄漏的情况。
Ext 官方推荐所有的componet类添加句柄时使用mon替代on

引用
//Old Style
this.el.on('click', this.onClick, this);

//New Style
this.mon(this.el, 'click', this.onClick, this);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics