更新:可能是 jQuery 的 trigger() 在测试中做了一些额外的工作,我打开了一个 issue在 github 上。
=====
我正在关注 learnQuery构建我的简单 jQuery。现在处理 DOM 事件,实现 on()
和 off()
函数。他们提供了一些测试,我无法通过其中一些测试。
这是我的代码:(你可以克隆 this branch ,运行 06.event_listeners/runner.html
来运行测试)
"use strict";
function isEmpty(str) {
return (!str || 0 === str.length);
}
// listener use to bind to DOM element, call corresponding functions when event firing.
function geneEventListener(event) {
console.log('gene');
let type = Object.keys(this.handlers).find(type=>type===event.type);
if (!type) return;
let functions = this.handlers[type];
functions.forEach(f=>f.apply(this,event));
}
// cache elements which bound event listener
let Cache = function () {
this.elements = [];
this.uid = 1;
};
Cache.prototype = {
constructor:Cache,
init:function (element) {
if(!element.uid) element.uid = this.uid++;
if(!element.handlers) element.handlers = {};
if(!element.lqListener) element.lqListener = geneEventListener.bind(element);
this.elements.push(element);
},
removeElement:function (uid) {
this.elements.splice(this.elements.findIndex(e=>e.uid===uid),1);
},
removeType:function (uid,type) {
if(this.get(uid)) delete this.get(uid).handlers[type];
},
removeCallback:function (uid, type, callback) {
if(this.get(uid) && this.get(uid).handlers[type]) {
let functions = this.get(uid).handlers[type];
functions.splice(functions.findIndex(callback),1)
}
},
// return element or undefined
get:function (uid) {
return this.elements.find(e=>e.uid===uid);
},
};
/*
* One type could have many event listeners, One element could have many event types of listeners
* So use element.handlers = {'click':[listener1, listener2, ...], 'hover':[...], ...}
* */
let eventListener = (function() {
let cache = new Cache();
function add (element, type, callback){
cache.init(element);
element.addEventListener(type,element.lqListener);
if(!element.handlers[type]){
element.handlers[type] = [];
}
(element.handlers[type]).push(callback);
}
// remove a type of event listeners, should remove the callback array and remove DOM's event listener
function removeType (element, type) {
element.removeEventListener(type,element.lqListener);
cache.removeType(element.uid,type);
}
// remove a event listener, just remove it from the callback array
function removeCallback(element, type, callback) {
cache.removeCallback(element.uid,type,callback);
}
// bind a callback.
function on(element,type,callback) {
if(!(element||type||callback)) throw new Error('Invalid arguments');
add(element,type,callback);
}
function off(element,type,callback) {
if(!(element instanceof HTMLElement)) throw new Error('Invaild element, need a instance of HMTLElement');
let handlers = cache.get(element.uid).handlers;
if(isEmpty(type)&&!callback){
for(let type in handlers){
removeType(element,type);
}
}
console.log('off')
if(!isEmpty(type)&&!callback) removeType(element,type);
if(!isEmpty(type) && (typeof callback === 'function')) removeCallback(element,type,callback);
}
return {
on,
off
}
})();
我使用 chrome 调试器来跟踪 element.handlers
的值,它看起来很好,在添加和删除回调时工作得很好。
并且测试在事件的回调函数中有一些console.log()
,奇怪的是,这些console.log()
不登录控制台,我试试在回调中设置断点,它也不起作用。
我对javascript经验不多,谁能告诉我怎么调试,哪里有bug,万分感谢!以及为什么 console.log()
不能在回调中工作。 它应该可以工作,因为他们在测试中编写了它,我认为。
测试代码如下:
/*global affix*/
/*global eventListener*/
describe('EventListeners', function() {
'use strict';
var $selectedElement, selectedElement, methods;
beforeEach(function() {
affix('.learn-query-testing #toddler .hidden.toy+h1[class="title"]+span[class="subtitle"]+span[class="subtitle"]+input[name="toyName"][value="cuddle bunny"]+input[class="creature"][value="unicorn"]+.hidden+.infinum[value="awesome cool"]');
methods = {
showLove: function(e) {
console.log('<3 JavaScript <3');
},
giveLove: function(e) {
console.log('==> JavaScript ==>');
return '==> JavaScript ==>';
}
};
spyOn(methods, 'showLove');
spyOn(methods, 'giveLove');
$selectedElement = $('#toddler');
selectedElement = $selectedElement[0];
});
it('should be able to add a click event to an HTML element', function() {
eventListener.on(selectedElement, 'click', methods.showLove);
$selectedElement.click();
expect(methods.showLove).toHaveBeenCalled();
});
it('should be able to add the same event+callback two times to an HTML element', function() {
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'click', methods.showLove);
$selectedElement.click();
expect(methods.showLove.calls.count()).toEqual(2);
});
it('should be able to add the same callback for two different events to an HTML element', function() {
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'hover', methods.showLove);
console.log('3')
$selectedElement.trigger('click');
$selectedElement.trigger('hover');
expect(methods.showLove.calls.count()).toEqual(2);
});
it('should be able to add two different callbacks for same event to an HTML element', function() {
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'click', methods.giveLove);
$selectedElement.trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
expect(methods.giveLove.calls.count()).toEqual(1);
});
it('should be able to remove one event handler of an HTML element', function() {
$selectedElement.off();
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'click', methods.giveLove);
eventListener.off(selectedElement, 'click', methods.showLove);
console.log('5')
$selectedElement.click();
expect(methods.showLove.calls.count()).toEqual(0);
expect(methods.giveLove.calls.count()).toEqual(1);
});
it('should be able to remove all click events of a HTML element', function() {
$selectedElement.off();
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'click', methods.giveLove);
eventListener.on(selectedElement, 'hover', methods.showLove);
eventListener.off(selectedElement, 'click');
console.log('6')
$selectedElement.trigger('hover');
$selectedElement.trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
expect(methods.giveLove).not.toHaveBeenCalled();
});
it('should be able to remove all events of a HTML element', function() {
$selectedElement.off();
eventListener.on(selectedElement, 'click', methods.showLove);
eventListener.on(selectedElement, 'click', methods.giveLove);
eventListener.on(selectedElement, 'hover', methods.showLove);
eventListener.off(selectedElement);
var eventHover = new Event('hover');
var eventClick = new Event('click');
selectedElement.dispatchEvent(eventClick);
selectedElement.dispatchEvent(eventHover);
expect(methods.showLove).not.toHaveBeenCalled();
expect(methods.giveLove).not.toHaveBeenCalled();
});
it('should trigger a click event on a HTML element', function() {
$selectedElement.off();
$selectedElement.on('click', methods.showLove);
eventListener.trigger(selectedElement, 'click');
expect(methods.showLove.calls.count()).toBe(1);
});
it('should delegate an event to elements with a given css class name', function() {
eventListener.delegate(selectedElement, 'title', 'click', methods.showLove);
$('.title').trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
});
it('should not delegate an event to elements without a given css class name', function() {
eventListener.delegate(selectedElement, 'title', 'click', methods.showLove);
$('.subtitle').trigger('click');
$('.title').trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
});
it('should delegate an event to elements that are added to the DOM to after delegate call', function() {
eventListener.delegate(selectedElement, 'new-element-class', 'click', methods.showLove);
var newElement = document.createElement('div');
newElement.className = 'new-element-class';
$selectedElement.append(newElement);
$(newElement).trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
});
it('should trigger delegated event handler when clicked on an element inside a targeted element', function() {
eventListener.delegate(selectedElement, 'title', 'click', methods.showLove);
var newElement = document.createElement('div');
newElement.className = 'new-element-class';
$selectedElement.append(newElement);
$('.title').append(newElement);
$(newElement).trigger('click');
expect(methods.showLove.calls.count()).toEqual(1);
});
it('should not trigger delegated event handler if clicked on container of delegator', function() {
var $targetElement = $('<p class="target"></p>');
$selectedElement.append($targetElement);
eventListener.delegate(selectedElement, 'target', 'click', methods.showLove);
$selectedElement.click();
expect(methods.showLove.calls.count()).toEqual(0);
});
it('should trigger delegated event handler multiple times if event happens on multiple elements', function() {
eventListener.delegate(selectedElement, 'subtitle', 'click', methods.showLove);
$('.subtitle').trigger('click');
expect(methods.showLove.calls.count()).toEqual(2);
});
it('should not trigger method registered on element A when event id triggered on element B', function() {
var elementA = document.createElement('div');
var elementB = document.createElement('div');
$selectedElement.append(elementA);
$selectedElement.append(elementB);
eventListener.on(elementA, 'click', methods.showLove);
eventListener.on(elementB, 'click', methods.giveLove);
$(elementA).trigger('click');
expect(methods.showLove).toHaveBeenCalled();
expect(methods.giveLove).not.toHaveBeenCalled();
});
});
最佳答案
问题在于没有调用hover
的事件。
只是 mouseenter
和 mouseleave
的组合。
您可以看到列出的所有事件类型 here .
当调用 element.addEventListener(type, element.lqListener)
对于类型值 hover
,它只是不起作用。
您可以从这个问题中看到更多信息 Is it possible to use jQuery .on and hover? .
关于javascript - 自制 jQuery 无法正确处理事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660605/