我目前正試圖提高自己的重構技巧,我有一段代碼,我寫了兩個非常相似的方法,並且我試圖圍繞簡化我的頭部臃腫的代碼,任何建議將受到歡迎。試圖瞭解JavaScript中的DRY原理
正如你所看到的,這兩種方法非常相似,唯一真正的區別是POST的URL。
authenticateA : function(e) {
var $this = $(e.target).closest('[data-fn]')
, text = $this.text()
, that = this;
$this.text('Authenticating...').addClass("auth-button-disable")
$.ajax({
type : 'POST',
url : '/A_authentications/update/',
data : { _method : 'PUT', sms_token : this.$el.find('#sms-input').val() },
complete: function(xhr) {
if (xhr.status === 200)
that.relocate();
else {
$this.text(text).removeClass("auth-button-disable");
that.handleError(xhr.status);
}
},
dataType : 'json'
});
},
authenticateB : function(e) {
var $this = $(e.target).closest('[data-fn]')
, text = $this.text()
, that = this;
$this.text('Authenticating...').addClass("auth-button-disable")
$.ajax({
type : 'POST',
url : '/B_authentications/',
data : { otp : this.$el.find('#B-input').val() },
complete: function(xhr) {
if (xhr.status === 200)
that.relocate();
else {
$this.text(text).removeClass("auth-button-disable");
that.handleError(xhr.status)
}
},
dataType : 'json'
});
}
我稱之爲一個事件的方法是單擊功能塊:
'click [data-fn="authenticate-A"]' : 'authenticateA',
'click [data-fn="authenticate-B"]' : 'authenticateB'
我想這可能是重構爲一個方法或兩個苗條的方法,我只是不知道從哪裏開始,再次感謝提前。
的到重構兩種方法成一個關鍵是確定什麼是兩個並可能這些差異在任何一個功能參數或從DOM元素中指定之間的差異。作爲一個起點,看起來url和類型是不同的,這些值可以來自
與'200'一起使用ajax'complete'方法是多餘的。只需使用'done'方法。 'complete'方法也被棄用。 – vsync 2015-03-31 17:09:15
使用'complete'參數[未棄用](http://stackoverflow.com/a/15821199/2788131)。 '.ajax({})。complete()',方法是。 – D4V1D 2015-03-31 17:13:19