francoischalifour / medium-zoom

🔎🖼 A JavaScript library for zooming images like Medium
https://medium-zoom.francoischalifour.com
MIT License
3.62k stars 165 forks source link

Add a destroy method #2

Closed cannap closed 7 years ago

cannap commented 7 years ago

Hi is there a simple way to destroy the click events and remove the class?

I use it in Combination with Vue and yea when i leave a component i should destroy the event which are no longer used

thx for the nice lib 💃

francoischalifour commented 7 years ago

Hi @cannap

There is unfortunately no such method in the API. I will however list 3 ideas that pop into my mind.

1. Using the pointer-events hack

This is the worst hack you could do, but adding a pointer-events: none; CSS style to your element should do the job...

2. Removing the event listeners on the targets

The mediumZoom object exports an images array that contains all the targets.

You should therefore be able to destroy the click events and remove the class by doing so:

const zoom = mediumZoom()
const { images } = zoom

images.forEach(elem => {
  elem.classList.remove('medium-zoom-image')
  elem.removeEventListener('click', onClick)
})

The onClick method will however be undefined, you'll probably need to use the getEventListeners JavaScript method.

3. Writing a new method in the library

I unfortunately won't have time to add this feature in the coming weeks. How about you send a pull request?

My naive guess would be to edit the src/medium-zoom.js file and:

  1. Create a destroy function
  2. Remove the appropriate event listeners and the style (see code below*)
  3. Export the new function (add destroy to the return statement l.225)
  4. Write the appropriate documentation in the README

(*) Remove the appropriate event listeners and the style:

images.forEach(elem => {
  elem.classList.remove('medium-zoom-image')
  elem.removeEventListener('click', onClick)
})

Let me know if you figure it out.

cannap commented 7 years ago

Hi, thx for this nice answer i will try first 2. later when i have time i add a method to the api and make a pr

francoischalifour commented 7 years ago

Hey @cannap, did you come up with a working solution?

cannap commented 7 years ago

omg i forgot this one sry^^ yea https://github.com/cannap/medium-zoom/blob/add-destroy/src/medium-zoom.js#L121-L130 but i need to create a new fork then i will submit a pr i messed something up