jquery外掛寫法

看風景就發表於2016-02-16

//傳統寫法

//全域性方法
;(function($){
    $.method = function(){

    }
    //or
    $.obj = {
        method1:function(){},
        method2:function(){}
    }
})(jQuery);
//物件方法
;(function ($){
  $.fn.myPlugin = function (options){
    var oSetting = $.extend(defaultOptions, options);
    return this.each(function (){
      
    });
  };
})(jQuery);

//物件導向寫法

;(function($){
    var fComponent = function($com){
            var self = this;
            this.$com = $com;
            //default params
            this.setting = {
                "width":1000,
                "height":270
            };
            $.extend(this.setting,this.getSetting());
    };
    fComponent.prototype = {
        //specified params
        getSetting:function(){
            var setting = this.$com.attr("data-setting");
            if(setting && setting != ""){
                return $.parseJSON(setting);
            }else{
                return {};
            };
        }
    };
    fComponent.fInit = function(a$com){
        var self = this;
        a$com.each(function(){
            new self($(this));
        });
    };
    window["fComponent"] = fComponent;
})(jQuery);

//dom
<div class='j-com' data-role='j-com' data-setting='{"width":"300px","height":"200px"}'></div>
//single
var oCom = new fComponent($('.j-com'));
//multiple
fComponent.init($(".j-com"));

 

相關文章