javascript 跨浏览器的事件系统(2)


dom.handleEvent = function (event) {
event = event || window.event
event = dom.fixEvent(event);
event.currentTarget = this;//修正currentTarget
var returnValue = true;
var handlers = this.events[event.type];
for(var i=0,n=handlers.length;i<n;i++){
if (handlers[i](event) === false) {
returnValue = false;
}
}
return returnValue;
};


在我们介绍的新版fixEvent函数时,我们先隆重介绍我从jQuery剽窃过来的伪事件对象。

复制代码 代码如下:


dom.oneObject = function(arr,val){
var result = {},value = val !== undefined ? val :1;
for(var i=0,n=arr.length;i<n;i++)
result[arr[i]] = value;
return result;
};
dom.mixin = function(result, source) {
if (arguments.length === 1) {
source = result;
result = dom;
}
if (result && source ){
for(var key in source)
source.hasOwnProperty(key) && (result[key] = source[key]);
}
if(arguments.length > 2 ){
var others = [].slice.call(arguments,2);
for(var i=0,n=others.length;i<n;i++){
result = arguments.callee(result,others[i]);
}
}
return result;
}
var MouseEventOne = dom.oneObject(["click","dblclick","mousedown",
"mousemove","mouseout", "mouseover","mouseup"],"[object MouseEvent]");
var HTMLEventOne = dom.oneObject(["abort","blur","change","error","focus",
"load","reset","resize","scroll","select","submit","unload"],"[object Event]");
var KeyboardEventOne = dom.oneObject(["keyup","keydown","keypress",],
"[object KeyboardEvent]");
var EventMap = dom.mixin({},MouseEventOne,HTMLEventOne,KeyboardEventOne)
var fn = "prototype";
dom.Event = function( src ) {
if ( !this.preventDefault ) {
return new dom.Event[fn].init( src );
}
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
//
dom.Event[fn] = {
init:function(src){
//如果传入的是事件对象
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
//如果传入的是事件类型
} else {
this.type = src;
}
this.timeStamp = new Date().valueOf();
this[ "expando" ] = true;
},
//http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/events.html#Conformance
toString:function(){
return EventMap[this.type] || "[object Event]"
},
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// 如果存在preventDefault 那么就调用它
if ( e.preventDefault ) {
e.preventDefault();
}
// 如果存在returnValue 那么就将它设为false
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// 如果存在preventDefault 那么就调用它
if ( e.stopPropagation ) {
e.stopPropagation();
}
// 如果存在returnValue 那么就将它设为true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
dom.Event[fn].init[fn] = dom.Event[fn];


这个构造函数只实现了W3C事件模型的少许方法,那些属性去了哪?不急,我们在fixEvent方法中通过拷贝方式实现它们。为了区别原生事件对象与伪事件对象,我们在它上面添加了一个expando属性。

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdsdgx.html