简体   繁体   中英

Calling a function before any click event handler

Hi I want to call a function every time before any click event handler method. I know, inside the click handler method I can call my function first, but this quite cumbersome as I have to do this at so many place as well as I have to keep in mind the same for any future click events.

You can set a capture event handler on the document object (or any common parent) and it will be called first before the event handler on the individual object. capture is the third argument to .addEventListener() which is normally optional and defaults to false , but if you pass true on a parent, then the event handler will be called first.

Here's an example:

 document.addEventListener("click", function() { log("document capture click"); }, true); document.getElementById("target").addEventListener("click", function() { log("element click"); }, false); function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div); } 
 <div id="target">Some text to click on</div> 

Here's a related question that helps to understand the capture flag: Unable to understand useCapture attribute in addEventListener

I see two solutions here.

First is to use onmousedown that is fired before click event

document.querySelector('.selector').addEventListener('mousedown', function(){
    console.log('mousedown');
}

document.querySelector('.selector').addEventListener('click', function(){
    console.log('click');
}

Other way is to use compose that will create new reusable function for you (npm i lodash.compose).

var compose = require(lodash.compose);
var firstFunc = function(e){
    console.log('first');
    return e; //if you want to use it in second function
};
var secondFunc = function(e) {
    console.log('second');
};

document.querySelector('.selector').addEventListener('click', compose(secondFunc, firstFunc));

Or you could save new func in variable;

var logFirstThanSecondOnClick = compose(secondFunc, firstFunc);
document.querySelector('.selector').addEventListener('click', logFirstThanSecondOnClick);

Simply compose do next

function compose(f, g) {
    return function(x) {
        return f(g(x));
    }
}

But lodash one is more complex inside.

Here is some math theory about function composition, if you are interested in https://en.wikipedia.org/wiki/Function_composition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM