【发布时间】:2011-09-09 02:27:38
【问题描述】:
在寻找优化代码质量的方法时,我最终遇到了 DRY(不要重复自己)的概念。我尽可能地遵循这一点,但有时我会遇到必须编写两个几乎相同的函数的位置,除了 2 或 3 行代码之外,我在试图找出最好的方法时用光了时间整理一下。
所以这是我的“问题”。我在下面包含了我几周前编写的两个函数,除了末尾的 3 行之外,它们基本相同,一个通过加法制作动画,另一个通过减法制作动画。我很想从其他开发人员那里获得一些关于他们将如何优化以下代码的意见或有一些不相关的代码示例,您解决了类似的问题。
/**
* Go to the previous notification
*
* @private
* @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
* @memberOf APP.devices
*/
function slideNext (cl) {
var button = $('#' + cl.id + cl.ss + cl.index),
index = cl.index - 1,
slider = devices[index].container.find('.slideContainer'),
// In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
if (button.hasClass('disabled')) {
return false;
}
slider.find('.active').removeClass('active').prev().addClass('active');
disableButtons(index);
slider.animate({'right': slidePos + notificationOffset}, 200, function () {
determineButtonState(index);
});
updatePositionContext(index);
}
/**
* Advance to the next notification
*
* @private
* @param {object} cl Click event details
* @memberOf APP.devices
*/
function slidePrev (cl) {
var button = $('#' + cl.id + cl.ss + cl.index),
index = cl.index - 1,
slider = devices[index].container.find('.slideContainer');
// In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
if (button.hasClass('disabled')) {
return false;
}
slider.find('.active').removeClass('active').next().addClass('active');
disableButtons(index);
slider.animate({'right': slidePos - notificationOffset}, 200, function () {
determineButtonState(index);
});
updatePositionContext(index);
// Load more notifications once user get's close to the end of the current set of notifications
if (slider.find('.active').nextAll().length == 3) {
getMoreNotifications(index);
}
}
【问题讨论】:
标签: javascript refactoring dry code-duplication