I am using a JQuery Mobile Accordion list
I'm listening for an expansion of one of the items using (in my pageshow
listener)
$("#myListSection").bind("expand",function(){})
In my app, pages are switched back and forth. I had a problem where multiple "expand" subscriptions would be created so when I would switch to the list again I'd have multiple functions being called when I expanded a section.
Therefore, I want to use the unbind
method when leaving the page to destroy the listener.
The problem I'm having is when I unbind the event and then try and rebind.
$("#myListSection").unbind("expand")
$("#myListSection").bind("expand")
Basically there is now only one expand event being fired (which is good), but the list section doesn't expand... I'm thinking the unbind destroyed more than just my listener.
JS Fiddle example: http://jsfiddle.net/6txWy/1658/
Simple. Set the functions you would like to execute as separate functions like this :
function expand() {..}
function collapse() {..}
Then your event handlers must be like this :
$('#my-collaspible').bind({
'expand': expand,
'collapse': collapse
});
I prefer passing functions like this because it makes my code clean and understandable. THEN, let's come to the main part. Instead of just using unbind
and removing all the functionality associated with the collapsible, use unbind
with the function you previously bound it to like this :
$(this).unbind('expand', expand);
where the second expand
is the anon function you passed. Later, when needed, the collapsible
could be bound back to expand()
like this. (again)
$(this).bind('expand', expand);
(Assuming this
is the collapsible here)
Demo : http://jsfiddle.net/hungerpain/6txWy/1661/
Extras - why jQuery deletes all event data associated with collapsible when unbind
is used : Collapsibles aren't native are they? They're fabricated by jQM by using a toggleClass, which, is in a function in itself and attached as a click
event handler. (Not completely how it works but you get the gist) So by just calling unbind
you're destroying everything.
Hope this helps :)
PS Please consider using the latest version of jQuery & jQuery mobile. There's a new kid in the block named on
which is far more better than bind
in a lot of ways.