This question already has an answer here:
My goal is to add some functionality to the bxslider script - in this case, I want to be able to enable/disable a keyboard event handler AFTER a slider is instantiated.
I guess this code is self explanatory, but it's ugly, it doesn't seem to be a good practice, and I have no idea of how to properly implement it. As you can see I'm very uncomfortable with that boolean argument which I don't know how to name it.
el.toggleKeyboard = function(a_boolean_variable){
if(!slider.initialized) return;
slider.settings.keyboardEnabled = a_boolean_variable;
}
I should call it slider.toggleKeyboard(true) to enable it and slider.toggleKeyboard(false) to disable it.
The private method related to it, which is called when the slider is instantiated:
var setupKeyboard = function(){ $(document).keydown(function(e){ if (e.keyCode == 39) { if (slider.settings.keyboardEnabled) clickNextBind(e); return false; } else if (e.keyCode == 37) { if (slider.settings.keyboardEnabled) clickPrevBind(e); return false; } }); }
Could anyone be so kind and shed a light on this for me? What design pattern should I use?
Thanks a lot!
EDIT
I came up with the following solution:
el.toggleKeyboard = function(shouldEnable){
if(!slider.initialized) return;
slider.settings.keyboardEnabled = (shouldEnable == undefined) ? !slider.settings.keyboardEnabled : shouldEnable;
}
It toggles keyboard navigation on/off and you can force by sending a boolean parameter (true to enable, false to disable).