I have two click events that are almost identical, I am trying to refactor to make it more DRY. I want share some lines of code in a handlerShared() function – but I loose the context of $(this) which should be the DOM element that is clicked. There are two different elements an svg and button. They have some specific functionality but alot of it is the same. I guess what I want is a way to make $(this) select the specific DOM element.
function handelerShared() {
}
function handlerTabs() {
var $this = $(this)
var dataKey = $this.attr("data-key");
pushHistory(dataKey);
removeActiveClass();
hideContent();
$(this).addClass(activeClass);
var activeTab = $(this).attr('href');
$(activeTab).fadeIn();
return false;
}
function handlerDiagram() {
var $this = $(this)
var dataKey = $this.attr("data-key")
pushHistory(dataKey);
removeActiveClass();
hideContent();
scrollToTabs();
$(themeTab + "." + dataKey).addClass(activeClass);
var activeSVGTab = $(themeContent + "." + dataKey)
$(activeSVGTab).fadeIn();
return false;
}
I m try to take these lines of of each handler and out into a handlerShared()
var $this = $(this)
var dataKey = $this.attr("data-key");
pushHistory(dataKey);
removeActiveClass();
hideContent();
the clicks
$(themeTab).on( "click", handlerTabs );
$(themeDiagram).on( "click", handlerDiagram );
>Solution :
I believe you can just pass the element around:
function handlerShared(element) {
var $this = $(element);
var dataKey = $this.attr("data-key");
pushHistory(dataKey);
removeActiveClass();
hideContent();
}
function handlerTabs() {
handlerShared(this);
$(this).addClass(activeClass);
var activeTab = $(this).attr('href');
$(activeTab).fadeIn();
return false;
}
function handlerDiagram() {
handlerShared(this);
scrollToTabs();
$(themeTab + "." + dataKey).addClass(activeClass);
var activeSVGTab = $(themeContent + "." + dataKey)
$(activeSVGTab).fadeIn();
return false;
}
$(themeTab).on("click", handlerTabs);
$(themeDiagram).on("click", handlerDiagram);