javascript – 自制jQuery无法正确处理事件

前端之家收集整理的这篇文章主要介绍了javascript – 自制jQuery无法正确处理事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:可能是jQuery的触发器()在测试中做了一些额外的工作,我在 github上打开了一个 issue.

=====

我正在关注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,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,callback) {
    cache.removeCallback(element.uid,callback);
  }

  // bind a callback.
  function on(element,callback) {
    if(!(element||type||callback)) throw new Error('Invalid arguments');
    add(element,callback);
  }

  function off(element,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,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',methods.showLove);
    eventListener.on(selectedElement,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','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',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,methods.giveLove);
    eventListener.off(selectedElement,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',methods.giveLove);
    eventListener.on(selectedElement,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',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',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',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','new-element-class',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',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',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','subtitle',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,methods.showLove);
    eventListener.on(elementB,methods.giveLove);

    $(elementA).trigger('click');

    expect(methods.showLove).toHaveBeenCalled();
    expect(methods.giveLove).not.toHaveBeenCalled();
  });
});

解决方法

问题在于没有称为悬停的事件.

只是mouseenter和mouseleave的组合.

您可以看到列出的所有事件类型here.

调用element.addEventListener时(type,element.lqListener)
使用类型值悬停,它只是不起作用.

你可以从这个问题Is it possible to use jQuery .on and hover?中查看更多信息.

猜你在找的jQuery相关文章