简体   繁体   中英

Javascript event on other element

On one element, is it possible to "subscribe" or listen for events on another element?

I have googled and checked SO, but no luck. I know no such event exist, but is there some clever hack or work around perhaps?...

pseudo code would be:

elementA.addEventListener("click on elementB", myScript);

edit: resolved. tanks everyone, i think i didnt explain properly. the way to do it is using proxy objects.

As far as I remember, you can try the following:

elementA.onclick = () =>{
    console.log('elementA clicked');
}

elementB.onclick = () => {
    elementA.click();
}

or modify it accordingly with element.on() :

elementA.addEventListener('click', () => {
    console.log('elementA clicked')
})

elementB.addEventListener('click', () => {
    elementA.click()
})

Suppose you have element A and you want a handler function to have access to it when the handler fires on element B. There are a couple of ways to achieve this:

const elemB = document.querySelector('#B');
elemB.addEventListener('click', evt => {
  const elemA = document.querySelector('#A');
  // do something with elemA
});

This is a ok solution if elemA is dynamically created/destroyed. A better solution if A is going to be around for a long time:

const elemA = document.querySelector('#A');
const handlerFactory = a => evt => {
  // do stuff with a
};
elemB.addEventListener('click', handlerFactory(elemA));

Now the handler logic can be reused with multiple elements and/or multiple event types.

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