A template for a jQuery plugin with options and accessible methods?

前端 未结 4 983
名媛妹妹
名媛妹妹 2021-02-10 05:57

I am want to build a plugin with accessible methods and options, this for a complex plugin. I need the methods to be accessible outside the plugin because if somebody ads someth

4条回答
  •  -上瘾入骨i
    2021-02-10 06:29

    An alternative:

    var Plugin = function($self, options) {
      this.$self = $self;
      this.options = $.extend({}, $.fn.plugin.defaults, options);
    };
    
    Plugin.prototype.display = function(){
      console.debug("Plugin.display");
    };
    
    Plugin.prototype.update = function() {
      console.debug("Plugin.update");
    };
    
    $.fn.plugin = function(option) {
      var options = typeof option == "object" && option;
    
      return this.each(function() {
        var $this = $(this);
        var $plugin = $this.data("plugin");
    
        if(!$plugin) {
          $plugin = new Plugin($this, options);
          $this.data("plugin", $plugin);
        }
    
        if (typeof option == 'string') {
          $plugin[option]();
        } else {
          $plugin.display();
        }
      });
    };
    
    $.fn.plugin.defaults = {
      propname: "propdefault"
    };
    

    Usage:

    $("span").plugin({
      propname: "propvalue"
    });
    

    $("span").plugin("update");
    

    This absurdly resembles the Twitter Bootstrap's JavaScript template. But, it wasn't completely taking from there. I have a long history of using .data().

    Don't forget to wrap it appropriately.

提交回复
热议问题