The Javascript code implements mock instantiation classes

  • 2020-05-26 07:45:30
  • OfStack

There are more and more things that Javascript can do, which leads to the problem of increasing the amount of Js code. In the face of increasing the amount of code, I chose to start the constructor in the instantiation of the image class automatically, and then I made all the js code to be classed in the form of registration.

code


/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HHJsLib Framework Apps
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */
 
HHJsLib.register({
  init: function() {
    this.bindPreviewBtn();
    this.bindUploadEleImageBtn();
    this.bindUploadEleAudioBtn('a.audio-upload-btn');
    this.bindUploadEleVideoBtn('a.video-upload-btn');
    this.bindDownloadEleAudioBtn();
    this.bindNewConBtn();
    this.bindDelConBtn('a.btn-del-con');
    this.bindDelItemBtn('a.btn-del-item');
    this.bindNewItemBoxClose('div.item-box');
    this.bindPlusBtn('a.btn-plus');
    this.bindAppendNewElement('div.new-item-box ul li a');
    this.bindSetPreviewVideo();
    this.bindAddAnswerBtn('a.btn-add-answer');
    this.bindDelAnswerBtn('a.btn-del-answer');
    this.bindDelImageBtn('a.btn-del-image');
    this.bindDelAudioBtn('a.btn-del-audio');
    this.initPlusBtn();
  },
  bindUploadEleVideoBtn: function(dom) {
    var self    = this;
    $(dom).click(function() {
      var $this  = $(this);
      var t    = HHJsLib.modal.confirm(
        ' Upload local video ',
        '<div class="text-center">'
        + ' <p> Browse through your computer and choose from it 1 Video files. </p>'
        + ' <div class="btn-box btn btn-blue">'
        + ' <div id="upload-btn"> Upload from the computer </div>'
        + ' </div>'
        + ' </div>'
      );
      var uploader  = HJZUploader.createVideo(
        '#upload-btn', 
        { 
          formData: {model: 'timeline'},
        },
        function(response) {
          if(false == response.rs) {
            self.setDemoBoxInit($this);
            return HHJsLib.warn(response.message);
          }
          self.setDemoAudioInfo($this, response.data);
          $('#dialog-box-' + t).modal('hide');
        }
      );
      uploader.on('uploadProgress', function(file) {
        self.setDemoBoxLoading($this);
      });
 
      return uploader;
    });
  },
  bindDelAudioBtn: function(dom) {
    this.bindDelFileBtn(dom, ' Do you really want to delete this audio? ');
  },
  bindDelImageBtn: function(dom) {
    this.bindDelFileBtn(dom, ' Do you really want to delete this image? ');
  },
  bindDelFileBtn: function(dom, msg) {
    var self  = this;
    $(dom).click(function() {
      var $target   = $(this);
      var t      = HHJsLib.initPopover($(this), msg);
      $('#btn-sure-' + t).click(function() {
        if(1 != $target.attr('data-new')) {
          $.get(
            queryUrl + 'timelineele/adel',
            {id: $target.attr('data-id')},
            function(response) {
              if(false === response.rs) {
                return HHJsLib.warn(response.message);
              }
              self.delDemoFieldInfo($target);
              $target.popover('destroy');
            }
          );
          return;
        }
        self.delDemoFieldInfo($target);
        $target.popover('destroy');
      });
    });
  },
  delDemoFieldInfo: function($target) {
    $($target.attr('data-demo-box')).html('');
    $($target.attr('data-box')).removeClass('uploaded').addClass('no-file');
    $($target.attr('data-field')).attr('data-id', '').attr('data-src', '');
  },
  bindAddAnswerBtn: function(dom) {
    var self  = this;
    $(dom).click(function() {
      var id     = $(this).attr('data-id');
      var answerHtml = eleTplMap.answerTpl.replace(/{id}/g, id);
      $('#answer-box-' + id).append(answerHtml);
      self.bindDelAnswerBtn('#answer-box-' + id + ' a.btn-del-answer');
    });
  },
  bindDelAnswerBtn: function(dom) {
    var self  = this;
    $(dom).click(function() {
      var $target = $(this);
      if(2 > $target.parent().parent().find('textarea.answer-editor').length) {
        return HHJsLib.warn(' At least 1 An answer! ');
      }
      var t    = HHJsLib.initPopover($target, ' Are you sure you want to delete this answer? ');
      $('#btn-sure-' + t).click(function() {
        $target.parent().remove();
      });
    });
  },
  bindAppendNewElement: function(dom) {
    var self    = this;
    $(dom).unbind('click').click(function() {
      var type  = $(this).attr('data-type');
      var heading   = $(this).parent().parent().attr('data-heading-id');
      if('heading' == type) {
        self.addNewElePartBox();
        $("#new-item-box-" + heading).hide();
        return;
      }
      self.addNewEleToPartBox(heading, type);
    });
  },
  addNewElePartBox: function() {
    var t      = this.getTimestamp();
    var partBoxHtml = eleTplMap.partBox.replace(/{t}/g, t);
    var headingHtml = this.initItemTplByType('heading', t, t);
    var itemHtml  = this.initItemTplByType('text', t, t);
    var itemBoxHtml = this.initItemBoxTpl(itemHtml, t, t, 'left', 'text');
    partBoxHtml   = partBoxHtml.replace(/{heading}/g, headingHtml);
    partBoxHtml   = partBoxHtml.replace(/{item}/g, itemBoxHtml);
    $("#main-box").append(partBoxHtml);
    this.bindDelItemBtn('#item-' + t + ' a.btn-del-item');
    this.movePlusBtnBox(t);
  },
  addNewEleToPartBox: function(heading, type) {
    var total    = $('#ele-part-box-' + heading + ' div.item-ele-box').length;
    var side    = total % 2 === 0 ? 'left' : 'right';
    var t      = this.getTimestamp();
    var itemHtml  = this.initItemTplByType(type, t, heading);
    var itemBoxHtml = this.initItemBoxTpl(itemHtml, heading, t, side, type);
    // So let's get rid of the height DIV
    $('#clearfix-' + heading).remove();
    $('#ele-part-box-' + heading).find('div.eles-box').append(itemBoxHtml);
    // The binding Dom The event 
    this.bindDelItemBtn('#item-' + t + ' a.btn-del-item');
    this.movePlusBtnBox(heading);
    this.bindNewEleUpload(type);
  },
  bindNewEleUpload: function(type) {
    var self  = this;
    switch(type) {
      case 'image':
      case 'question':
      case 'know':
      self.bindUploadModal('a.btn-upload');
      break;
      case 'audio':
      self.bindUploadEleAudioBtn('a.audio-upload-btn');
      self.bindDelAudioBtn('a.btn-del-audio');
      break;
    }
  },
  initItemTplByType: function(type, t, heading) {
    var itemHtml  = eleTplMap[type].replace(/{t}/g, t);
    itemHtml    = itemHtml.replace(/{sort_num}/g, this.getNewEleSortNum(heading));
 
    return itemHtml.replace(/{headingId}/g, heading);
  },
  initItemBoxTpl: function(content, heading, t, side, type) {
    var itemBoxHtml = eleTplMap.itemBox.replace(/{t}/g, t);
    itemBoxHtml   = itemBoxHtml.replace(/{headingId}/g, heading);
    itemBoxHtml   = itemBoxHtml.replace(/{side}/g, side);
    itemBoxHtml   = itemBoxHtml.replace(/{content}/g, content);
    itemBoxHtml   = itemBoxHtml.replace(/{hash}/g, hex_md5(t));
    itemBoxHtml   += '<div class="clearfix" id="clearfix-' + heading + '"></div>';
     
    return itemBoxHtml.replace(/{type}/g, type);
  },
  movePlusBtnBox: function(heading) {
    // Delete the original 
    $('#new-item-box-' + heading).remove();
    // Adding new 
    var plusBtnHtml   = eleTplMap.plusBtn.replace(/{headingId}/g, heading);
    $(plusBtnHtml).insertBefore('#clearfix-' + heading);
    var $items     = $('#ele-part-box-' + heading).find('div.item-ele-box');
    if($items.length < 2) {
      $($items[0]).find('a.btn-del-item').hide();
    } else {
      $($items[0]).find('a.btn-del-item').show();
    }
    // The binding event 
    this.bindAppendNewElement('#new-item-box-' + heading + " ul.new-item-list-box li a");
    this.bindPlusBtn('#btn-plus-' + heading);
  },
  bindNewItemBoxClose: function(dom) {
    $(dom).click(function() {
      $('div.new-item-box').hide();
    });
  },
  bindPlusBtn: function(dom) {
    $(dom).click(function(event) {
      $('div.new-item-box').hide();
      var id = $(this).attr('data-heading-id');
      $('#new-item-box-' + id + ' div.new-item-box').removeClass('hide').attr('data-show', '1').show();
      event.preventDefault();
    });
  },
  initPlusBtn: function() {
    var self  = this;
    $('div.ele-part-box').each(function() {
      var dataId   = $(this).attr('data-heading');
      self.movePlusBtnBox(dataId);
    });
  },
  bindDelItemBtn: function(dom) {
    var self  = this;
    $(dom).click(function() {
      var $target = $(this);
      var t    = HHJsLib.initPopover($target, ' Are you sure you want to delete this? ');
      var id   = $target.attr('data-id');
      var heading = $('#item-' + id).attr('data-heading-id');
      $('#btn-sure-' + t).click(function() {
        if(1 == $target.attr('data-new')) {
          $.get(
            queryUrl + 'timelineele/adel',
            {id: $target.attr('data-id')},
            function(response) {
              if(false === response.rs) {
                return HHJsLib.warn(response.message);
              }
              $('#item-' + id).fadeOut('fast', function() {
                $(this).remove();
                self.movePlusBtnBox(heading);
                self.reArrangeItem(heading);
              });
              $target.popover('destroy');
            }
          );
          return;
        }
        $target.popover('destroy');
        $('#item-' + id).fadeOut('fast', function() {
          $(this).remove();
          self.movePlusBtnBox(heading);
          self.reArrangeItem(heading);
        });
      });
    });
  },
  reArrangeItem: function(heading) {
    var rank  = 1;
    $('#ele-part-box-' + heading).find('div.item-ele-box').each(function() {
      if(rank % 2 === 0) {
        $(this).removeClass('pull-left item-left')
        .addClass('pull-right item-right');
      } else {
        $(this).removeClass('pull-right item-right')
        .addClass('pull-left item-left');
      }
      rank ++;
    });
  },
  bindNewConBtn: function() {
    var self  = this;
    $('#btn-new-con-item').click(function() {
      var t  = self.getTimestamp();
      var conItemHtml   = eleTplMap.conItemTpl.replace(/{t}/g, t);
      $('#conclusion-box').append(conItemHtml);
      self.bindDelConBtn('#btn-del-con-' + t);
      self.bindUploadModal('a.btn-upload');
    });
  },
  bindDelConBtn: function(dom) {
    var self  = this;
    $(dom).click(function() {
      var $target = $(this);
      var t    = HHJsLib.initPopover($target, ' Are you sure you want to delete this conclusion? ');
      var id   = $target.attr('data-id');
      $('#btn-sure-' + t).click(function() {
        if(1 == $target.attr('data-new')) {
          $.get(
            queryUrl + 'timelineele/adel',
            {id: $target.attr('data-id')},
            function(response) {
              if(false === response.rs) {
                return HHJsLib.warn(response.message);
              }
              $('#item-con-' + id).fadeOut('fast', function() {
                $(this).remove();
              });
              $target.popover('destroy');
            }
          );
          return;
        }
        $target.popover('destroy');
        $('#item-con-' + id).fadeOut('fast', function() {
          $(this).remove();
        });
      });
    });
  },
  getNewEleSortNum: function(heading) {
    return parseInt(this.getMaxSortNum(heading)) + 1;
  },
  getMaxSortNum: function(heading) {
    var sortNums  = [];
    $('.ele-sort-' + heading).each(function() {
      sortNums.push($(this).val());
    });
    sortNums    = sortNums.sort(function(a, b) {
      if (a === b) {
         return 0;
      }
      if (typeof a === typeof b) {
        return a > b ? -1 : 1;
      }
      return typeof a > typeof b ? -1 : 1;
    });
 
    return sortNums[0] == null ? 0 : sortNums[0];
  },
  bindUploadEleImageBtn: function() {
    this.bindUploadModal('a.btn-upload');
  },
  bindUploadEleAudioBtn: function(dom) {
    var self    = this;
    $(dom).click(function() {
      var $this  = $(this);
      var t    = HHJsLib.modal.confirm(
        ' Upload the audio ',
        '<div class="text-center">'
        + ' <p> Browse through your computer and choose from it 1 Two audio files. </p>'
        + ' <div class="btn-box btn btn-blue">'
        + ' <div id="upload-btn"> Upload from the computer </div>'
        + ' </div>'
        + ' </div>'
      );
      var uploader  = HJZUploader.createAudio(
        '#upload-btn', 
        { 
          formData: {model: 'timeline'},
        },
        function(response) {
          if(false == response.rs) {
            self.setDemoBoxInit($this);
            return HHJsLib.warn(response.message);
          }
          self.setDemoAudioInfo($this, response.data);
          $('#dialog-box-' + t).modal('hide');
        }
      );
      uploader.on('uploadProgress', function(file) {
        self.setDemoBoxLoading($this);
      });
 
      return uploader;
    });
  },
  setDemoAudioInfo: function($target, data) {
    var audioHtml  = '<audio controls="controls"><source src="' + siteUrl + data.src + '" /></audio>';
    $($target.attr('data-demo-box')).html(audioHtml).show();
    $($target.attr('data-field')).attr('data-id', data.id).attr('data-src', data.src);
  },
  bindUploadModal: function(dom) {
    var self    = this;
    $(dom).unbind('click').click(function() {
      var $this  = $(this);
      var t    = HHJsLib.modal.confirm(
        ' To upload pictures ',
        '<div class="text-center">'
        + ' <p> Browse through the pictures on your computer and choose from them 1 Zhang. </p>'
        + '<div class="btn-box btn btn-blue">'
        + ' <div id="upload-btn"> Upload from the computer </div>'
        + ' </div>'
        + ' </div>'
      );
      var uploader  = HJZUploader.createImage(
        '#upload-btn', 
        { 
          formData: {model: 'timeline'}
        },
        function(response) {
          if(false == response.rs) {
            self.setDemoBoxInit($this);
            return HHJsLib.warn(response.message);
          }
          var imgHtml   = '<img src="'
            + siteUrl + response.data.src
            + '" alt="' + response.data.name + '" />';
          $($this.attr('data-demo-box')).html(imgHtml).show();
          $($this.attr('data-field')).val(response.data.id).attr('data-src', response.data.src);
          $('#dialog-box-' + t).modal('hide');
        }
      );
      uploader.on('uploadProgress', function(file) {
        self.setDemoBoxLoading($this);
      });
      self.bindDelImageBtn('a.btn-del-image');
 
      return uploader;
    });
  },
  bindPreviewBtn: function() {
    var self  = this;
    $('#edit-btn, #preview-btn').click(function() {
      try{
        self.verifyBaseInfo();
        self.verifyEleInfo();
        self.verifyConclusionInfo();
        $('#timeline-form').submit();
      }catch(e) {
        return HHJsLib.warn(e);
      }
    });
  },
  verifyBaseInfo: function() {
    HHJsLib.isEmptyByDom('#image-path', ' Large timeline ');
    HHJsLib.isEmptyByDom('#cover', ' Timeline cover ');
    HHJsLib.isEmptyByDom('#name', ' The title ');
    HHJsLib.isEmptyByDom('#description', ' describe ');
  },
  verifyEleInfo: function() {
    this.verifyHeaderEleInfo();
    this.verifyTextEleInfo();
    this.verifyImageEleInfo();
    this.verifyVideoEleInfo();
    this.verifyAudioEleInfo();
    this.verifyQuestionEleInfo();
    this.verifyKnowEleInfo();
  },
  verifyHeaderEleInfo: function() {
    $('div.item-heading-box').each(function() {
      HHJsLib.isEmpty($(this).find('textarea').val(), ' The headline content ');      
    });
  },
  verifyTextEleInfo: function() {
    $('div.item-text-box').each(function() {
      HHJsLib.isEmptyByDom('#ele-text-' + $(this).attr('data-id'), ' Text content element ');
    });
  },
  verifyImageEleInfo: function() {
    $('div.item-image-box').each(function() {
      HHJsLib.isEmptyByDom('#ele-image-hash-' + $(this).attr('data-id'), ' Picture address ');
      HHJsLib.isEmptyByDom('#ele-image-content-' + $(this).attr('data-id'), ' Photo show ');
    });
  },
  verifyVideoEleInfo: function() {
    $('div.item-video-box').each(function() {
      HHJsLib.isEmptyByDom('#ele-video-hash-' + $(this).attr('data-id'), ' Video address ');
      HHJsLib.isEmptyByDom('#ele-video-content-' + $(this).attr('data-id'), ' Video introduction ');
    });
  },
  verifyAudioEleInfo: function() {
    $('div.item-audio-box').each(function() {
      HHJsLib.isEmptyByDom('#ele-audio-hash-' + $(this).attr('data-id'), ' Audio address ');
      HHJsLib.isEmptyByDom('#ele-audio-content-' + $(this).attr('data-id'), ' Audio is introduced ');
    });
  },
  verifyQuestionEleInfo: function() {
    $('div.item-question-box').each(function() {
      HHJsLib.isEmptyByDom('#ele-question-content-' + $(this).attr('data-id'), ' Problem of content ');
      HHJsLib.isEmptyByDom('#ele-question-extend-' + $(this).attr('data-id'), ' Explanation of answers to questions ');
      HHJsLib.isEmpty(answerLen, ' Answers to questions ');
      $('#answer-box-' + $(this).attr('data-id')).find('textarea').each(function() {
        HHJsLib.isEmpty($(this).val(), ' Answers to questions ');
      });
    });
  },
  verifyKnowEleInfo: function() {
    $('div.item-know-box').each(function() { 
      HHJsLib.isEmptyByDom('#ele-know-hash-' + $(this).attr('data-id'), ' Know the image address ');
      HHJsLib.isEmptyByDom('#ele-know-content-' + $(this).attr('data-id'), ' Know to introduce ');
    });
  },
  verifyConclusionInfo: function() {
    var length     = $('#conclusion-box div.item-con').length;
    HHJsLib.isEmpty(length, ' conclusion ');
    $('#conclusion-box div.item-con').each(function() {
      var dataId = $(this).attr('data-id');
      HHJsLib.isEmptyByDom('#ele-con-hash-' + dataId, ' Conclusion images ');
      HHJsLib.isEmptyByDom('#ele-con-content-' + dataId, ' Summary of the details ');
    });
  },
  bindDownloadEleAudioBtn: function() {
    var self  = this;
    $('a.download-audio-btn').click(function() {
      var $this    = $(this);
      try{
        HHJsLib.isEmptyByDom("#item-audio-upload-hash-" + $this.attr('data-id'), ' Download address ');
        var url   = $("#item-audio-upload-hash-" + $this.attr('data-id')).val();
        if('mp3' != url.substring(url.lastIndexOf('.') + 1).toLowerCase()) {
          return HHJsLib.warn(' Format not supported, must be Mp3 Format! ');
        } 
        var t    = HHJsLib.modal.info(
          ' Download audio ',
          '<p class="text-center"> Please wait while downloading the audio file ...<p>'
        );
        self.setDemoBoxLoading($this);
        $.getJSON(
          siteUrl + 'index.php/public/resource/adownload', 
          {url: encodeURIComponent(url)}, 
          function(response) {
            if(false == response.rs) {
              self.setDemoBoxInit($this);
              return HHJsLib.warn(response.message);
            }
            $('#dialog-box-' + t).modal('hide');
            self.setDemoAudioInfo($this, response.data);
          }
        );
      } catch(e) {
        return HHJsLib.warn(e);
      }
    });
  },
  setDemoBoxLoading: function($target) {
    $($target.attr('data-box')).removeClass('no-file').addClass('uploaded');
    $($target.attr('data-file-box')).html('');
  },
  setDemoBoxInit: function($target) {
    $($target.attr('data-box')).removeClass('uploaded').addClass('no-file');
    $($target.attr('data-file-box')).html('');
  },
  bindSetPreviewVideo: function() {
    $('input.ele-video').change(function() {
      var url   = $(this).val();
      if(url != '') {
        if('swf' != url.substring(url.lastIndexOf('.') +1 ).toLowerCase()) {
          return HHJsLib.warn(' The video address is illegal, please enter valid online viewing Flash Address! ');
        }
        var previewHtml   = '<embed src="' + url + '" quality="high" width="495" height="220" align="middle" allowScriptAccess="always" allowFullScreen="true" mode="transparent" type="application/x-shockwave-flash"></embed>';
        $($(this).attr('data-demo-box')).html(previewHtml);
      }
    });
  },
  bindDelEleBtnFormEdit: function() {
     this.bindDelUploadImgBtn();
  },
   getTimestamp: function() {
     return (new Date()).getTime();
   }
});

That's all I want to share with you in this article. I hope it will be helpful for you to learn javascript.


Related articles: