js模塊化之路(1):手寫js組件

閱讀前需要具備js基礎(this,js原型鏈,繼承,立即執行函數等)

關鍵點:
1.通過立即執行函數,來達到隱藏細節的目的
2.防止污染全局變量
3.代碼解耦,提高復用性

下面是三個我總結的組件例子

  1. 原生js版:
var myModule = (function(){

    function _myModule(ct){
      this.ct = ct;
      this.init(); //初始化
      this.render(); //渲染
      this.bind(); //綁定事件
    }

    _myModule.prototype = { //定義原型方法
      init: function(){
        this.var1 = 1;
        this.var2 = 2;
      },

      render: function(){
        xxx
      },

      bind: function(){
        xxx
      },

      fn1: function(){
        xxxxxx
      },

      fn2: function(){
        xxxxxx
      }
    }

    return {
      init: function(cts){ 
        cts.forEach(function(ct){
          new _myModule(ct)
        });
      }
    }
})();

//假設頁面有多個div.box
myModule.init(document.querySelectorAll('.box'))

2.jQuery版:

var myModule = (function(){

    function _myModule(ct){
      this.ct = ct;
      this.init(); //初始化
      this.render(); //渲染
      this.bind(); //綁定事件
    }

    _myModule.prototype = { //定義原型方法
      init: function(){
        this.var1 = 1;
        this.var2 = 2;
      },

      render: function(){
        xxx
      },

      bind: function(){
        xxx
      },

      fn1: function(){
        xxxxxx
      },

      fn2: function(){
        xxxxxx
      }
    }

    return {
      init: function($ct){ 
        $ct.each(function(index, ct){
          new _myModule($(ct));
        });
      }
    }
})();

//假設頁面有多個div.box
myModule.init($('.box'));

3.jQuery插件版:

var myModule = (function(){

    function MyModule(ct){
      this.ct = ct;
      this.init(); //初始化
      this.render(); //渲染
      this.bind(); //綁定事件
    }

    MyModule.prototype = { //定義原型方法
      init: function(){
        this.var1 = 1;
        this.var2 = 2;
      },

      render: function(){
        xxx
      },

      bind: function(){
        xxx
      },

      fn1: function(){
        xxxxxx
      },

      fn2: function(){
        xxxxxx
      }
    }

    return {
      //給jQuery對象添加方法
      init: $.fn.MyModule = function(){
              this.each(function(){
                new myModule($(this));
              });
            }  
    }

})();

//假設頁面有多個div.box
$(".box").MyModule();

理解上面三個例子后,
可以做幾個實例或者嘗試把自己以前做的功能組件化。

附帶幾個我做的組件化demo,demo中可以看到兩個組件互不干擾:
1.輪播組件
點擊查看源碼

2.懶加載(曝光)組件
點擊查看源碼

3.Tab組件
點擊查看源碼

4.日歷組件
點擊查看源碼

5.modal組件
點擊查看源碼

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容