Example of native implementation of FastClick event in js

高洛峰
Release: 2016-12-06 13:34:19
Original
1999 people have browsed it

Note: I have not been learning JavaScript for a long time. I have been working on mobile web pages and WeChat applications on the web recently. Since I have recently used functions similar to fastclick, I used touchstart and touchend events to simulate them in the original program. Now I am trying to encapsulate them. The following two problematic solutions were obtained. Share it with everyone, and ask for guidance from the master

In mobile web app development, the 300ms delay of the click event will cause slow response, especially in low-end machines. Using touchstart or touchend events will conflict with the default wheel event, which is not what we expect.

So, I did it myself, had enough food and clothing, and wrote a native js code for a quick click event (considering the environment of web app development, we do not need to consider compatibility with browsers such as IE for the time being).

Implementation method 1 is as follows:

function FastClickEvent(handler){
  var fastclick = {
    handler : handler,
    bind : function(query){
      var targetList = document.querySelectorAll(query);
      for(var i=0,len=targetList.length;i<len;i++)
      {
        targetList[i].addEventListener(&#39;touchstart&#39;,handleEvent);
        targetList[i].addEventListener(&#39;touchend&#39;,handleEvent);
      }
    },
    unbind : function(query){
      var targetList = document.querySelectorAll(query);
      for(var i=0,len=targetList.length;i<len;i++)
      {
        targetList[i].removeEventListener(&#39;touchstart&#39;,handleEvent);
        targetList[i].removeEventListener(&#39;touchend&#39;,handleEvent);
      }
    } 
  }
  var touchX = 0 ,touchY = 0;
 
  function handleEvent(event){
    switch(event.type)
    {
      case &#39;touchstart&#39;:
        touchX = event.touches[0].clientX;
        touchY = event.touches[0].clientY;
        break;
      case &#39;touchend&#39;:
        var x = event.changedTouches[0].clientX;
        var y = event.changedTouches[0].clientY;
        if(Math.abs(touchX-x)<5||Math.abs(touchY-y)<5)
          fastclick.handler(event);
        break;
    }
  };
 
  return fastclick;
};
Copy after login

Principle: Based on the change in position when continuous touchstart and touchend events occur, determine whether it is a click

Call: Use a handler function to register a FastClickEvent event. Then bind the registered FastClickEvent event to the corresponding element through the bind method. As follows:

var handler = function(event){
  console.log(event.target.id+" fastclicked");
}
var fastClick = new FastClickEvent(handler);
fastClick.bind("div");
Copy after login

In this code, we register the fastclick handler event for all div elements. Call fastClick.unbind to unbind an element.

But there is a problem with this code, in order to allow the handleEvent event to access touchX, touchY. I used a closure method, which means that every time a new FastClickEvent event object is created, a repeated handleEvent function must be injected into the memory. As for the repeated touchX and touchY, there is no need to say more.

Newbie help: I ​​originally wanted to write the handleEvent function into the prototype, but a problem arises is that the this object of handleEvent (event) is windows, that is to say, I cannot get the touchX, touchY and handler objects, causing an access error. .

There is a relatively simple solution, which is to only register one fastClickEvent event, and then determine the response content in the handler based on the actual value of event.target (that is, the object where the event occurs).

However, this means you must be very familiar with all fastclick events.

The advantage of using this method is that since you only have one handleEvent function, basically, before the page is released, unless you don’t want to trigger the fastclick event anymore, you don’t need to unbind the fastclick event of any element (even if If you unbind it, the handler function still exists in the memory). Moreover, you can easily use bind(query) to add the fastclick event of any dynamically generated element, as long as you have written the corresponding handler in the handler function.

If you want to add multiple fastclick events, and you may need to register them in multiple places, you only need to create a new FastClickEvent object and bind it to the corresponding element.

The following is a method of using the EventTarget class. First, let’s take a look at the EventTarget

function EventTarget(){
  this.handlers = {};
}
EventTarget.prototype = {
  constructor: EventTarget,
  addHandler : function(type,handler){
    if(typeof this.handlers[type] == "undefined"){
      this.handlers[type]=[];
    }
    this.handlers[type].push(handler);
  },
  fire : function(event){
    if(!event.target){
      event.target = this;
    }
    if(this.handlers[event.type] instanceof Array){
      var handlers = this.handlers[event.type];
      for(var i=0,len=handlers.length;i<len;i++){
        handlers[i](event);
      }
    }
  },
  removeHandler : function(type,handler){
    if(this.handlers[type] instanceof Array){
      var handlers = this.handlers[type];
      for(var i=0,len=handler.length;i<len;i++){
        if(handlers[i]==handler){
          break;
        }
      }
      handlers.splice(i,1);
    }
  }
}
Copy after login

class, which is an interface used to add, remove and implement custom classes. Refer to "JavaScript Advanced Programming Third Edition" P616-617

So, how to turn this class into our fastclick event interface?

Define a global variable and use this variable to complete all fastclick event registration, deletion and addition

var FastClick = function(){
 
  var fastclick = new EventTarget(),
    touchX = 0 ,
    touchY = 0;
 
  function handleEvent(event){
    switch(event.type)
    {
      case &#39;touchstart&#39;:
        touchX = event.touches[0].clientX;
        touchY = event.touches[0].clientY;
        break;
      case &#39;touchend&#39;:
        var x = event.changedTouches[0].clientX;
        var y = event.changedTouches[0].clientY;
        if(Math.abs(touchX-x)<5||Math.abs(touchY-y)<5)
          fastclick.fire({type:&#39;fastclick&#39;,target:event.target});
        break;
    }
  };
  fastclick.bind = function(query)
  {
    var targetList = document.querySelectorAll(query);
    for(var i=0,len=targetList.length;i<len;i++)
    {
      targetList[i].addEventListener(&#39;touchstart&#39;,handleEvent);
      targetList[i].addEventListener(&#39;touchend&#39;,handleEvent);
    }
  }
 
  Fastclick.unbind = function(query){
    var targetList = document.querySelectorAll(query);
    for(var i=0,len=targetList.length;i<len;i++)
    {
      targetList[i].removeEventListener(&#39;touchstart&#39;,handleEvent);
      targetList[i].removeEventListener(&#39;touchend&#39;,handleEvent);
    }
  }
  return fastclick;
}();
Copy after login

This global variable FastClick can be used to add any fastclick event.

Let’s talk about how to call it.

Add event function:

FastClick.addHandler('fastclick',function(event){});

Delete event function: //Anonymous events cannot be deleted

FastClick.removeHandler('fastclick',handler);

Binding elements

FastClick.bind("div");

Unbinding

FastClick.unbind("div");

Using this method, we also need to predict the event.target in the handler event , because although this method can add multiple fastclick events, the events are executed one by one in sequence during execution, which means that functions you do not want to execute may be executed. The benefit of

is that multiple fastclick events can be registered and executed without binding again.
For example,

FastClick.bind("div");
FastClick.addHandler(handler1);
FastClick.addHandler(handler2);
Copy after login

Then, when a quick click event occurs on any div element, handler1 and handler2 will be executed sequentially.

If we call removeHandler to delete handler1 or handler2, the corresponding function will no longer be executed.

In addition, it should be noted that in the handler function, this object is the array FastClick.handlers['fastclick']. Generally, we use event.target to obtain the object where the event occurred.

Using this method basically overcomes the problems of the above method. Moreover, repeating new for this object does not make much sense unless you don’t want to predict the event.target and generate a lot of FaskClick classes, but this Obviously it's not efficient.

Newbie help: How can I implement a binding execution function for a specific element, that is: I can call FastClick.bind(query,handler); to implement the fastclick event of adding a handler to elements that meet the query conditions.


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template