-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JS-util #5
Comments
DOM event // 监听事件, DOM0, DOM2, IE
var addEvent = function(elem, type, handler, useBubble) {
if(elem.addEventListener) {
elem.addEventListener(type, handler, useBubble);
}else if(elem.attachEvent) {
elem.attachEvent('on'+type, function(){
handler.call(elem)
});
}else {
elem['on' + type] = handler;
}
};
// 事件取消注册
var delEvent = function(elem, type, handler, useBubble) {
if(elem.removeEventListener) {
elem.removeEventListener(type, handler, useBubble);
}else if(elem.detachEvent) {
elem.detachEvent('on'+type, handler);
}else {
elem['on' + type] = null;
}
}
// 阻止事件冒泡,IE只有冒泡过程
var stopPropagation = function (elem ) {
if(elem.stopPropagation) {
elem.stopPropagation();
}else {
elem.cancelBubble = true;
}
}
// 取消默认行为
var preventDefault = function(event) {
if(event.preventDefault) {
event.preventDefault();
}else {
event.returnValue = false;
}
}
// 获取事件目标
var getTarget = function(event) {
return event.target || event.srcElement;
}
// 获取事件对象
var getEvent = function(event) {
return event || window.event; // IE下的事件对象实在wind
} |
发布,订阅模式 ES6class Event {
constructor() {
this.events = {};
}
// 注册事件
on(type,cb) {
if( this.events.hasOwnProperty(type) ) {
this.events[type].push(cb)
}
this.events[type] = [cb]
}
// 移除事件
off(type) {
if( this.events.hasOwnProperty(type) ) {
delete this.events[type]
}
}
// 触发事件
emit(type, ...args) {
this.events[type].forEach( cb => {
cb(args)
})
}
}
var event = new Event();
event.on('transmit', (args) => {
console.log('成功注册事件 '+args)
})
event.emit('transmit','我是触发事件传入的参数','参数2'); //
event.off('transmit');
event.emit('transmit','1'); //"TypeError: Cannot read property 'forEach' of undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sub,sup实现
The text was updated successfully, but these errors were encountered: