javascript - 重构 JavaScript 原型(prototype)构造函数中的重复代码

标签 javascript jquery

我有一个 open 函数,一旦触发,只需在专用面板中播放视频即可。

此函数可以通过两种方式触发 - 一种通过点击,另一种通过页面加载(窗口加载)以及包含有效 anchor 标记的 url 来触发。

它们都工作正常,但窗口加载处理程序的一些代码是重复的,我不太确定如何保持这个干燥。

请看一下并给我指出一些方向,告诉我如何才能写得更好。 我在 open 函数中评论了它的用途。

$.videoWatch.prototype = {
  init: function() {
    this.$openLinks = this.$element.find(".open");
    this.$closeLinks = this.$element.find(".close");
    this.open();
    this.close();
  },
  _getContent: function(element) {
    var $parent = element.parent(),
        id = element.attr('href').substring(1),
        title = $parent.data('title'),
        desc = $parent.data('desc');

        return {
          title: title,
          desc: desc,
          id: id
        }
  },
  open: function() {

    var self = this;

    //open theatre with window load with #hash id
    window.onload = function() {
        var hash = location.hash;

        var $a = $('a[href="' + hash + '"]'),
            content = self._getContent($a),
            $li = $a.parents("li"),
            $theatreVideo = $(".playing"),
            $theatreTitle = $(".theatre-title"),
            $theatreText = $(".theatre-text");

        $(".theatre").attr('id', content.id);
        $theatreTitle.text(content.title);
        $theatreText.text(content.desc);

        if ($theatreText.text().length >= 90) {
          $(".theatre-text").css({
            'overflow': 'hidden',
            'max-height': '90px',
          });
          $moreButton.insertAfter($theatreText);
        }

        $a.parent().addClass("active");
        $(".theatre").insertAfter($li);
        $(".theatre").slideDown('fast', scrollToTheatre);
        oldIndex = $li.index();

    }

    //open theatre with click event
    self.$openLinks.on("click", function(e) {
      // e.preventDefault();
      if (curID == $(this).parent().attr("id")) {
        $("figure").removeClass("active");
        $("button.more").remove();
        $(".theatre").slideUp('fast');
        $('.playing').attr("src", "");
        removeHash();
        oldIndex = -1;
        curID = "";
        return false
      } else {
        curID = $(this).parent().attr("id");
      }

      var $a = $(this),
          content = self._getContent($a),
          $li = $a.parents("li"),
          $theatreVideo = $(".playing"),
          $theatreTitle = $(".theatre-title"),
          $theatreText = $(".theatre-text");


      $(".theatre").attr('id', content.id);
      $theatreTitle.text(content.title);
      $theatreText.text(content.desc);

      if ($theatreText.text().length >= 90) {
          $(".theatre-text").css({
            'overflow': 'hidden',
            'max-height': '90px',
          });
          $moreButton.insertAfter($theatreText);
      }

      if (!($li.index() == oldIndex)) {
        $("figure").removeClass("active");
        $(".theatre").hide(function(){
          $a.parent().addClass("active");
          $(".theatre").insertAfter($li);
          $(".theatre").slideDown('fast', scrollToTheatre);
          oldIndex = $li.index();
        });
      } else {
        $(".theatre").insertAfter($li); 
        scrollToTheatre();
        $("figure").removeClass("active");
        $a.parent().addClass("active");
      } 
    });
  },

  ...

最佳答案

简化和重构的open方法:

open: function() {

    var self = this;
    var serviceObj = {
        theatreVideo : $(".playing"),
        theatre: $(".theatre"),
        theatreTitle : $(".theatre-title"),
        theatreText : $(".theatre-text"),
        setTheatreContent: function(content){
            this.theatre.attr('id', content.id);
            this.theatreTitle.text(content.title);
            this.theatreText.text(content.desc);

            if (this.theatreText.text().length >= 90) {
               this.theatreText.css({
                   'overflow': 'hidden',
                   'max-height': '90px',
               });
               $moreButton.insertAfter(this.theatreText);
            }
        },
      activateTeatre: function(a, li){
          a.parent().addClass("active");
          this.theatre.insertAfter(li);
          this.theatre.slideDown('fast', scrollToTheatre);
          oldIndex = li.index();
      }

    };

    //open theatre with window load with #hash id
    window.onload = function() {
        var hash = location.hash;
        var $a = $('a[href="' + hash + '"]'),
            content = self._getContent($a),
            $li = $a.parents("li");

       serviceObj.setTheatreContent(content);
       serviceObj.activateTeatre($a, $li);

    }

    //open theatre with click event
    self.$openLinks.on("click", function(e) {
      // e.preventDefault();
      if (curID == $(this).parent().attr("id")) {
        $("figure").removeClass("active");
        $("button.more").remove();
        $(".theatre").slideUp('fast');
        $('.playing').attr("src", "");
        removeHash();
        oldIndex = -1;
        curID = "";
        return false
      } else {
        curID = $(this).parent().attr("id");
      }

      var $a = $(this),
          content = self._getContent($a),
          $li = $a.parents("li");

      serviceObj.setTheatreContent(content);

      if (!($li.index() == oldIndex)) {
        $("figure").removeClass("active");
        $(".theatre").hide(function(){
          serviceObj.activateTeatre($a, $li);
        });
      } else {
        $(".theatre").insertAfter($li); 
        scrollToTheatre();
        $("figure").removeClass("active");
        $a.parent().addClass("active");
      } 
    });
  },

关于javascript - 重构 JavaScript 原型(prototype)构造函数中的重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982432/

相关文章:

javascript - 如何在 react-router-dom 中实现像 vue-router 这样的路由器离开守卫?

javascript - 基于ajax动态定位列表项

javascript - 除了服务器端回调之外,我如何调用 javascript 函数?

javascript - 如何使用输入复选框检查特定图像

jquery - magento 上的 fancybox 混合内容问题

javascript - 异步加载 json 作为对象属性,然后在事件中访问它

javascript - 将 dat.GUI 严格放置在 THREE.js 场景中,不使用 <iframe>

javascript - 如何使用 JavaScript 或 CSS 仅显示 H2 标题的第一个单词

javascript - 如何使用 jquery ajax 将 css 样式添加到动态加载的代码片段

php - 使用 PHP 在页面向下滚动时加载 Ajax 数据