Search code examples
jqueryswipe.js

Proper way to 'setup on-demand' and 'reset' jQuery plugins such as swipe.js?


I'm building a PhoneGap app where I'd like to use swipe.js--which is a 'swipable' and auto-animated carousel.

To set it up, you declare it as such:

window.mySwipe = new Swipe(document.getElementById('slider'), { (parameters here) });

This is fine, and does what it should. But I'd like to set it up only on demand. Since this is in a modal, there's no reason to set it up until the modal is shown, and then if closed, I'd like it to go away as there's no reason to keep animating through the carousel when it's not visible. (Though minor, I assume it's a bit of a performance hit to have something in perpetual animation that isn't actually seen on screen)

My question is: what is the proper way set up a jQuery plugin like this on-demand as well as disable (destroy?) on-demand?

Or is this a feature that the plugin has to support in the first place?

UPDATE:

So, 'setup on-demand' is easy enough. I can simply wrap the above in a function and call that function only when needed:

function setUpSwipe(){
    window.mySwipe = new Swipe(document.etc...
}

But I'm still sumped on how to 'destroy' this after I no longer need it. I've tried 'delete':

function destroySwipe(){
    delete window.mySwipe; 
}

That does nothing (I assume because window.mySwipe is not exposed to this particular functon?)

I also tried setting the object to a blank variable:

function destroySwipe(){
    window.mySwipe = "";
}

But that was just a stab in the dark so didn't expect it to actually work. :)


Solution

  • Looking at the source swipe.js supports a kill method that stops the timer and removes any event listeners.