【问题标题】:Abstractize jQuery plugin creation抽象 jQuery 插件创建
【发布时间】:2013-11-29 00:59:22
【问题描述】:

目前我正在使用这个“模板”构建我的 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 中做到这一点......

【问题讨论】:

    标签: javascript jquery object jquery-plugins


    【解决方案1】:

    这是插件模式:

    (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);
    

    最后,您的代码将是相同的,但更长且多余。

    【讨论】:

    • 其实是想返回this而不是$(this)
    【解决方案2】:

    插件可以是您想要的简单或复杂。样板模板是一个足够可靠的框架,可以使用它开发非常强大的 API,包括动态更改选项设置。

    与所有 javascript 代码一样,它们有许多不同的样式来编写插件。您不受任何准则或规则的约束。如果您希望插件能够链接,唯一的绝对规则是返回this。之后,样板中的所有其他内容都是可选的。您在左大括号和右大括号之间放置的内容可以是适合您的需求或编码风格的任何内容

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 2016-07-23
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多