练习笔记-EVENT

貌似有很多都不能捕获。需要再加强。

(function(window,$,undefined){
var event = {
cache:{},
timeMark: function( dom, name ){
if(name){
var timeMark = name+$.date();
dom.setAttribute('alfred',timeMark);
return timeMark;
}
else{
return dom.getAttribute('alfred');
}
},
add: function( dom, evt, data, fn, handle ){
var timeMark = this.timeMark(dom) || this.timeMark(dom,'event'),
callback = function(e){
var e = e ||window.event;
if(e.originalTarget ==dom|| e.srcElement==dom){
fn.call(dom);
}
};

this.cache[timeMark] = this.cache[timeMark] ||{};
this.cache[timeMark][evt] = {
target: dom,
event: evt,
data: data,
callback: callback,
fns:fn,
handle: handle
}
if(dom.attachEvent)
{
dom.attachEvent("on"+evt,callback);
}
if(dom.addEventListener)
{
dom.addEventListener(evt,callback,handle);
}
return dom;
},
fire: function(dom,evt,data){
var timeMark = this.timeMark(dom);
if( this.cache[timeMark] && this.cache[timeMark][evt] ){
this.cache[timeMark][evt].fns.call(dom,data);
}
return dom;
},
remove: function(dom,evt){
var timeMark = this.timeMark(dom),
events = this.cache[timeMark][evt];
if(dom.detachEvent)
{
dom.detachEvent( "on"+evt ,events.callback );
}
if(dom.removeEventListener)
{
dom.removeEventListener( evt, events.callback, events.handle );
}
delete this.cache[timeMark][evt];
return dom;
},
eventAble: function(it){
if(!it || $.isString(it))
{
return false;
}
it.add = function(evt,data,fn){
this[evt] = [];
if($.isFunction(data))
{
fn = data;
data = null;
}
this[evt].data = data;
this[evt].push(fn);
return this;
};
it.fire = function(evt,data)
{
var fns = this[evt], i = 0;
if( fns && fns.length )
{
for( ;i<this[evt].length;i++ )
{
this[evt][i].call(this,data);
}
}
return this;
};
it.remove = function(evt)
{
delete this[evt];
return this;
};
}
};
$.event = {
bind: function(dom,evt,data,fn,handle){
if($.isFunction(data))
{
handle = !!fn;
fn = data;
data = "";
}
if($.isDom(dom) || dom === window)
{//dom
return event.add(dom,evt,data,fn,handle);
}
//not dom
event.eventAble(dom);
return dom.on(evt,data,fn);
},
unbind: function(dom,evt){
if($.isDom(dom) || dom === window)
{
return event.remove(dom,evt);
}
if(dom.wipe)
{
return dom.wipe(evt);
}
},
trigger: function(dom, evt, data){
if($.isDom(dom) || dom === window)
{
return event.fire(dom, evt, data);
}
if(dom.fire)
{
return dom.fire(evt,data);
}
}
}
})(window,alfred)

可以对DOM,FN,OBJECT,ARRAY 也就是非字符数字的都应该可以做事件,还不完善。再找思路优化。。。



posted @ 2012-03-05 22:11  AlfredLee  阅读(423)  评论(2编辑  收藏  举报