簡體   English   中英

抽象化jQuery插件創建

[英]Abstractize jQuery plugin creation

目前,我正在使用此“模板”構建jQuery插件:

;(function($, window, document){

  var defaultOptions = {
        option1: value1,
        option2: value2,
      };

  function plugin(el, options){

    this.options  = $.extend({}, defaultOptions, options);
    this.el = el;

    this.__construct();
  };

  plugin.prototype = {

    __construct: function(){
      // do the plugin stuff, set up events etc.
    },

    __destruct: function(){   
      $(this.el).removeData('myPlugin');
    },

    // other plugin functions here...
  };

  $.fn.myPlugin = function(options){
    var additionalArguments = Array.prototype.slice.call(arguments, 1);

    return this.each(function(){
      var inst = $.data(this, 'myPlugin');

      if(!(inst instanceof plugin)){
        var inst =  new plugin(this, options);
        $.data(this, 'myPlugin', inst); 
        return inst;
      }  

      if(typeof options == 'string'){
        inst[options].apply(inst, additionalArguments);
      }  
    });
  };

  $(document).ready(function(){
    $('.my-plugin').myPlugin();  
  });

})(jQuery, window, document);

我從https://github.com/jquery-boilerplate/jquery-boilerplate/blob/master/src/jquery.boilerplate.js獲得了大部分想法

因此,此示例實際上沒有執行任何操作,僅是插件的“主干”,並且您可以看到它是很多代碼。

我可以構建某種插件創建器功能,使我可以將上面的代碼重寫為更小的代碼嗎:

createPlugin('myPlugin', {

  defaultOptions: {},

  __construct: function() { 
    ...
  },

  __destruct: function() { 
    ...
  },

  somePublicFunction: function(){
    ...
  }

});

但是仍然可以像

$('.element').myPlugin();

在PHP中,我將使用抽象類來進行此類操作,但是我不確定如何在javascript中進行操作...

這是插件模式:

(function ($){

  $.fn.myPlugin = function (options){
    // do something or not to do
    // anyway it will work
    return(this);//because 'this' will return the input selector 
  };

})(jQuery);

這足夠的代碼來實現基本功能。

如果需要一些createjQueryPlugin(name, methods)函數,可以使用YES 只需將$.fn.myPlugin包裝在函數定義中,但仍然必須定義名稱空間:

(function ($){    
//...
})(jQuery);

最后,您的代碼將相同,但是更長且多余。

插件可以像您想要的那樣簡單或復雜。 樣板模板是一個足夠堅固的框架,因此可以使用它來開發非常健壯的API,包括即時更改選項設置。

與所有javascript代碼一樣,它們用於編寫插件的樣式很多。 您不受任何准則或規則的約束。 唯一的絕對規則是,如果您希望插件具有鏈接能力,則返回this 之后,樣板中的其他所有內容都是可選的。 放在開括號和閉括號之間的內容可以是您想要的任何適合您的需要或編碼樣式的內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM