如何在jQuery多点击事件函数间共享$(this)上下文实现DRY重构
保留jQuery事件上下文的DRY重构方案
要把重复代码提取到共享函数同时不丢失$(this)的上下文,有两种简单的实现方式:
方式一:用call绑定上下文到共享函数
直接在专属事件处理函数里调用共享函数时,用call把当前的this(触发点击的DOM元素)传递过去,这样共享函数里的this就会指向正确的元素。
修改后的代码如下:
共享函数实现
function handlerShared() { var $this = $(this); var dataKey = $this.attr("data-key"); pushHistory(dataKey); removeActiveClass(); hideContent(); // 返回dataKey给后续专属逻辑复用,避免重复获取 return dataKey; }
专属事件处理函数
function handlerTabs() { var dataKey = handlerShared.call(this); // 绑定当前元素上下文 $(this).addClass(activeClass); var activeTab = $(this).attr('href'); $(activeTab).fadeIn(); return false; } function handlerDiagram() { var dataKey = handlerShared.call(this); // 绑定当前元素上下文 scrollToTabs(); $(themeTab + "." + dataKey).addClass(activeClass); var activeSVGTab = $(themeContent + "." + dataKey); $(activeSVGTab).fadeIn(); return false; }
事件绑定代码(无需修改)
$(themeTab).on("click", handlerTabs); $(themeDiagram).on("click", handlerDiagram);
方式二:给共享函数传递元素参数
如果觉得call的写法不够直观,也可以直接把$(this)作为参数传给共享函数,明确指定操作的元素:
共享函数实现
function handlerShared($element) { var dataKey = $element.attr("data-key"); pushHistory(dataKey); removeActiveClass(); hideContent(); return dataKey; }
专属事件处理函数
function handlerTabs() { var $this = $(this); var dataKey = handlerShared($this); $this.addClass(activeClass); var activeTab = $this.attr('href'); $(activeTab).fadeIn(); return false; } function handlerDiagram() { var $this = $(this); var dataKey = handlerShared($this); scrollToTabs(); $(themeTab + "." + dataKey).addClass(activeClass); var activeSVGTab = $(themeContent + "." + dataKey); $(activeSVGTab).fadeIn(); return false; }
两种方式都能完美保留$(this)的上下文,同时实现代码复用,你可以根据自己的习惯选择。
内容的提问来源于stack exchange,提问作者Adam Adams
相关产品推荐
相关产品推荐

