繁体   English   中英

试图在Javascript中理解DRY原则

[英]Trying to understand DRY principles in Javascript

我目前正在努力提高我的重构技能,我有一个代码块,我已经编写了两个非常相似的方法,我试图简化我的膨胀代码,欢迎任何建议。

正如您所看到的,这两种方法非常相似,唯一真正的区别是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'

我认为这些可以重构为一种方法或两种更简洁的方法,我只是不确定从哪里开始,再次提前感谢。

您可以拥有一个生成这些功能的函数:

generateAuthFunction : function( authDetails) {
  return 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 : authDetails.url,
      data : authDetails.dataFunc(this),
      complete: function( xhr ) {

        if ( xhr.status === 200 )
          that.relocate();
        else {
          $this.text( text ).removeClass("auth-button-disable");
          that.handleError( xhr.status );
        }
      },
      dataType : 'json'
    });
  };
}

然后你生成它:

var authDetailsA = {
  url :  '/A_authentications/update/',
  dataFunc : function (this) {
    return { _method : 'PUT', sms_token : this.$el.find( '#sms-input' ).val() };
  }
};
var authDetailsB = {
  url :  '/B_authentications/',
  dataFunc : function (this) {
    return { otp : this.$el.find( '#B-input' ).val() };
};
authenticateA : generateAuthFunction(authDetailsA);
authenticateB : generateAuthFunction(authDetailsB);

您可以像以前一样调用它:

'click [data-fn="authenticate-A"]' : 'authenticateA',
'click [data-fn="authenticate-B"]' : 'authenticateB'

我认为这甚至可能带来不必要的复杂性,但它更加干燥。

  1. 摘要你的要求。 将您的应用逻辑混合到您的视图中只会混淆图片。 让我们创建一个Authentication模块:

     var Authentication = (function(Backbone, _) { function whoGoesThere(opts) { opts = _.extend({}, opts, { type : 'POST', dataType: 'json' }); return Backbone.$.ajax(opts); } return { A: function(data) { data = _.extend({}, data, { _method : 'PUT' }); return whoGoesThere({ url : '/A_authentications/update/', data: data }); }, B: function(data) { return whoGoesThere({ url : '/B_authentications/', data: data }); } }; })(Backbone, _); 
  2. 配置视图以使用函数而不是函数名来处理事件,将值传递给前一个模块上的相应方法,然后将返回的promise委托给公共处理程序:

     events: { 'click [data-fn="authenticate-A"]': function(e) { var promise = Authentication.A({ sms_token : this.$el.find( '#sms-input' ).val() }); this.onAuthentication(e, promise); }, 'click [data-fn="authenticate-B"]': function(e) { var promise = Authentication.B({ otp : this.$el.find( '#B-input' ).val() }); this.onAuthentication(e, promise); } } 
  3. 处理promise(这里是Ajax对象,但可以是任何东西)

     onAuthentication: function(e, promise) { var $this = $(e.target).closest('[data-fn]') , text = $this.text() , that = this; $this.text( 'Authenticating...' ).addClass("auth-button-disable"); promise.done(function() { that.relocate(); }); promise.fail(function(xhr) { that.handleError(xhr.status); }); promise.always(function() { $this.text(text).removeClass("auth-button-disable"); }); } 

和演示http://jsfiddle.net/s3ydy3u6/1/

试试(未经测试的代码):

authenticate: function(t, e) { // t = 'A' || 'B'
  var $this = $( e.target ).closest( '[data-fn]' )
  ,   text = $this.text()
  ,   that = this
  ,   url
  ,   data;

  $this.text( 'Authenticating...' ).addClass("auth-button-disable")

  // conditionnaly set up your variables
  if(t == 'A') {
      data = { _method : 'PUT', sms_token : this.$el.find( '#sms-input' ).val() }; 
      url = '/A_authentications/update/';
  } else if(t == 'B') {
      url = '/B_authentications/';
      data = { otp : this.$el.find( '#B-input' ).val() };
  }

  $.ajax({
    type : 'POST',
    url : url, // use them
    data : data, // use them
    complete: function( xhr ) {

      if ( xhr.status === 200 )
        that.relocate();
      else {
        $this.text( text ).removeClass("auth-button-disable");
        that.handleError( xhr.status );
      }
    },
    dataType : 'json'
  });
},

您只需检查authenticate函数中的data-fn属性即可。

authenticate: function (e) {        
        var $this = $(e.target).closest('[data-fn]'),
            text = $this.text(),
            that = this;
        $this.text('Authenticating...').addClass("auth-button-disable");
        var fn = $this.data("fn");

        switch (fn) {
            case "authenticate-A":
                data = {
                    _method: 'PUT',
                    sms_token: this.$el.find('#sms-input').val()
                };
                url = '/A_authentications/update/';
                break;
            case "authenticate-B":
                data = {
                    otp: this.$el.find('#B-input').val()
                };
                url = '/B_authentications/update/';
                break;

        }

        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            complete: function (xhr) {

                if (xhr.status === 200) that.relocate();
                else {
                    $this.text(text).removeClass("auth-button-disable");
                    that.handleError(xhr.status);
                }
            },
            dataType: 'json'
        });


    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM