在javascript中简化/模块化我的代码

时间:2015-05-17 12:15:39

标签: javascript

我知道我应该在编码时遵循DRY原则。但是,我不是那样的javascript,所以我想问一下如何让下面的代码更具可读性和可操作性。

$('#frontfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = frontvImageIsLoaded;
    });
    $('#rearfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = rearvImageIsLoaded;
    });
    $('#rightfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = rightvImageIsLoaded;
    });
    $('#leftfile_v').change(function(){
        reader = Main.Mod.image_change(this);
        reader.onload = leftvImageIsLoaded;
    });
    //called after an image file has been chosen
    function frontvImageIsLoaded(e) {
        $("#frontimagepreview").attr('src', e.target.result);
        $("#frontpreview-msg").css('color', 'green');  
    };
    function rearvImageIsLoaded(e) {
        $("#rearimagepreview").attr('src', e.target.result);
        $("#rearpreview-msg").css('color', 'green');   
    };
    function rightvImageIsLoaded(e) {
        $("#rightimagepreview").attr('src', e.target.result);
        $("#rightpreview-msg").css('color', 'green');  
    };
    function leftvImageIsLoaded(e) {
        $("#leftimagepreview").attr('src', e.target.result);
        $("#leftpreview-msg").css('color', 'green');   
    };

这是Main.Mod.image_change()

的代码
 var image_change = function handleFileImageChange(obj){
            //holds the image preview object

            var file = obj.files[0];
            var imagefile = file.type;
            var match= ["image/jpeg","image/png","image/jpg"];

            if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]))){
              alert("Incorrect image file. You still be able to upload this form but the system " + 
               "will be using the default image.");
              $("#preview-msg").css('color', 'red');
              return false;
            }else{
                var reader = new FileReader();
                //reader.onload = imageIsLoaded;
                reader.readAsDataURL(obj.files[0]); 

              return reader;
            }
        };

上面的代码,将处理文件输入更改事件,然后根据文件输入更改img src。

我知道我编写的代码非常糟糕,因为我必须多次重复我的代码。如何以更有效的方式实现它?

感谢。

2 个答案:

答案 0 :(得分:1)

  1. 使用,组合选择器:

    $('#frontfile_v,#rearfile_v').change(function(){
        // ... 
    })
    
  2. “change”事件将绑定到选择器匹配的每个对象。这样您就不需要复制绑定了。

    1. 通过传递参数将“图像加载”函数合并到一个函数中:

      var idsMap = {
         leftfile_v : {preview : '#frontimagepreview', msg : '#frontpreview-msg'},
         // etc...
      };
      
      $('#leftfile_v,#rearfile_v').change(function(){
          var ids = idsMap[$(this).attr('id')];
          reader = Main.Mod.image_change(this);
          reader.onload = function(e) {
              imageIsLoaded(e, ids.preview, ids.msg);
          };
      });
      
      function imageIsLoaded(e, preview, msg) {
          $(preview).attr('src', e.target.result);
          $(msg).css('color', 'green');  
      };
      

答案 1 :(得分:1)

另一种变体。如@Malki所说:在选择器中使用逗号

$('#frontfile_v, #rearfile_v,#rightfile_v,#leftfile_v').change(function(){
    var id = this.id.replace(/file_v$/,'');
    reader = Main.Mod.image_change(this);
    if(reader){ //for case when `image_change` return not "false"
        // use mode generic function
        reader.onload = function(e){
            $("#"+id+"imagepreview").attr('src', e.target.result);
            $("#"+id+"preview-msg").css('color', 'green'); 
        };
    }
});

至于handleFileImageChange,您需要使用Array.indexOf函数

var image_change = function handleFileImageChange(obj){
    //holds the image preview object

    var file = obj.files[0];
    var imagefile = file.type;
    var match= ["image/jpeg","image/png","image/jpg"];

    if(match.indexOf(imagefile) == -1){
        alert("Incorrect image file. You still be able to upload this form but the system will be using the default image.");
        $("#preview-msg").css('color', 'red');
        return false; 
    }else{
        var reader = new FileReader();
        //reader.onload = imageIsLoaded;
        reader.readAsDataURL(file); //you not need use "obj.files[0]" because you already save it in "var file"

        return reader;
    }
};