Jquery: enable / disable a function? (bind / unbind?) best way to do this?
I have a function stickyhead() that basically keeps an h2 fixed at the top of the page, as you scroll down the page the text in the h2 changes as you reach a new h2, so it's like the phonebook/contacts of an iphone or android phone. A header with the letter A will stick to the top as you scroll through your contacts that have names starting with A, then it changes the text in the header at the top of the page to B when you reach the B names. I want to enable/disable this when .switch
label has class selected. The code below work开发者_运维百科 just fine, but I'm wondering if this is a bad way to do it? Am I reloading my function multiple times? Is there a better way to do it?
$('.switch').click(function() {
if ($('.switch label').hasClass('selected')) {
stickyhead();
} else {
$(window).unbind('scroll');
}
});
//Assuming I've understood the scenario correctly, wouldn't this work.
$('.switch').delegate("label.selected", "click", function() {
if (stickyheadActive){
//do your stuff here
}
else{
return;
}
});
But do keep in mind, not unbinding handlers when predictably not required is a waste of memory. Binding/Unbinding are ugly but justifiable when resources are scarce.
Also, when elements are removed and handlers remain binded... Viola! Perfect case for memory leaks. Might seem irrelevant, but just felt I should mention this, just in case you're writing this for mobile platforms.
I'm struggling slightly to visualise your code, but it's unlikely that you need to be constantly binding and unbinding. You should have a boolean in your scroll handler that conditionally runs the code in the handler:
var doStickyHead = true;
$(window).scroll(function(){
if (doStickyHead) {
// do your code
}
});
$('.switch').click(function(){
doStickyHead = !doStickyHead; // invert the value of doStickyHead
});
It may be more efficient to keep the function binded but to use a status variable to determine whether stickyhead()
actually does anything or not.
eg
function stickyhead(){
if (!stickyheadActive) return; //Guard clause to prevent action
//...Your current code...//
}
Then rather than unbinding the function just use stickyheadActive=false;
精彩评论