5

我想构建一个具有可访问方法和选项的插件,这适用于一个复杂的插件。我需要可以在插件外部访问这些方法,因为如果有人向 DOM 广告一些东西,它需要更新(所以我们不需要再次运行完整的插件)。

我过去看到有这样的插件,但我找不到它们,所以我不能看它们。我还是 javascript 的新手,所以任何帮助都会很好。

如果我们仍然可以全局覆盖这些选项,那就太好了。

我想如何使用插件:

// options
$('#someid').myplugin({name: 'hello world'});

// methods(would be nice if we can use this)
$('#someid').myplugin('update');

// 我的旧插件包装器

;(function($, window, document, undefined){

    $.fn.pluginmyPlugin = function(options) { 

        options = $.extend({}, $.fn.pluginmyPlugin.options, options); 

            return this.each(function() {  

                var obj = $(this);

                // the code 
            });     
        };

        /**
        * Default settings(dont change).
        * You can globally override these options
        * by using $.fn.pluginName.key = 'value';
        **/
        $.fn.pluginmyPlugin.options = {
            name: '',
                            ...         
        };

})(jQuery, window, document);

更新

因此,在查看了 jQuery 文档后,我构建了以下代码,如果代码有问题,请告诉我,如果可以更好地构建......

;(function($, window, document, undefined){

    var methods = {

        init : function( options ) {

            options = $.extend({}, $.fn.pluginmyPlugin.options, options); 

            return this.each(function(){

            alert('yes i am the main code')

            });
        },
        update : function( ) {
             alert('updated')
        }
    };

    $.fn.pluginmyPlugin = function(method) { 

        if ( methods[method] ) {
          return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( 'Method ' +  method + ' does not exist on this plugin' );
        }    

    };

        /**
        * Default settings(dont change).
        * You can globally override these options
        * by using $.fn.pluginName.key = 'value';
        **/
        $.fn.pluginmyPlugin.options = {
            name: 'john doe',
            //....
        };

})(jQuery, window, document);
4

4 回答 4

3

替代:

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"
};

用法:

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

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

这荒谬地类似于Twitter Bootstrap 的 JavaScript 模板。但是,它并没有完全从那里拿走。我有很长的使用历史.data()

不要忘记适当地包装它。

于 2012-12-08T13:44:01.210 回答
2

如果你想像这样使用插件:

// Init plugin
$('a').myplugin({
    color: 'blue'
});

// Call the changeBG method
$('a').myplugin('changeBG')
    // chaining
    .each(function () {
        // call the get method href()
        console.log( $(this).myplugin('href') );
    });

或者如果您需要每个元素独立的插件实例:

$('a').each(function () {
    $(this).myplugin();
});

你会想要像这样设置你的插件:

/*
 *  Project: 
 *  Description: 
 *  Author: 
 *  License: 
 */

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window is passed through as local variable rather than global
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    var pluginName = "myplugin",
        // the name of using in .data()
        dataPlugin = "plugin_" + pluginName,
        // default options
        defaults = {
            color: "black"
        };

    function privateMethod () {
        console.log("private method");
    }

    // The actual plugin constructor
    function Plugin() {
        /*
         * Plugin instantiation
         *
         * You already can access element here
         * using this.element
         */
         this.options = $.extend( {}, defaults );
    }

    Plugin.prototype = {

        init: function ( options ) {

            // extend options ( http://api.jquery.com/jQuery.extend/ )
            $.extend( this.options, options );

            /*
             * Place initialization logic here
             */
            this.element.css( 'color', 'red' );
        },

        destroy: function () {
            // unset Plugin data instance
            this.element.data( dataPlugin, null );
        },

        // public get method
        href: function () {
            return this.element.attr( 'href' );
        },

        // public chaining method
        changeBG: function ( color = null ) {
            color = color || this.options['color'];
            return this.element.each(function () {
                // .css() doesn't need .each(), here just for example
                $(this).css( 'background', color );
            });
        }
    }

    /*
     * Plugin wrapper, preventing against multiple instantiations and
     * allowing any public function to be called via the jQuery plugin,
     * e.g. $(element).pluginName('functionName', arg1, arg2, ...)
     */
    $.fn[pluginName] = function ( arg ) {

        var args, instance;

        // only allow the plugin to be instantiated once
        if (!( this.data( dataPlugin ) instanceof Plugin )) {

            // if no instance, create one
            this.data( dataPlugin, new Plugin( this ) );
        }

        instance = this.data( dataPlugin );

        /*
         * because this boilerplate support multiple elements
         * using same Plugin instance, so element should set here
         */
        instance.element = this;

        // Is the first parameter an object (arg), or was omitted,
        // call Plugin.init( arg )
        if (typeof arg === 'undefined' || typeof arg === 'object') {

            if ( typeof instance['init'] === 'function' ) {
                instance.init( arg );
            }

        // checks that the requested public method exists
        } else if ( typeof arg === 'string' && typeof instance[arg] === 'function' ) {

            // copy arguments & remove function name
            args = Array.prototype.slice.call( arguments, 1 );

            // call the method
            return instance[arg].apply( instance, args );

        } else {

            $.error('Method ' + arg + ' does not exist on jQuery.' + pluginName);

        }
    };

}(jQuery, window, document));

笔记:

  • 此样板文件不会为每个方法调用使用 .each(),您应该在需要时使用 .each()
  • 允许重新初始化插件,但只会创建 1 个实例
  • 包括销毁方法的示例

参考:https ://github.com/jquery-boilerplate/jquery-boilerplate/wiki/jQuery-boilerplate-and-demo

于 2013-07-24T00:20:59.743 回答
1

你试过jQuery UI Widget Factory吗?

有一点学习曲线,但我现在喜欢它,处理选项,默认值和允许方法,让所有东西都紧紧包裹起来非常漂亮:)


编辑

jQuery UI Widget Factory 是 jQuery UI 库的一个独立组件,它提供了一种简单的、面向对象的方式来创建有状态的 jQuery 插件。

有状态插件和小部件工厂简介

我认为在大多数情况下,额外的开销并不值得担心。这些天我用 coffescript 写东西,一切都被编译、压缩和压缩,所以这里和那里的一些额外的行并没有太大的区别。我对网站速度的研究似乎表明 HTTP 请求的数量很重要——确实,让我走上这条轨道的前同事曾为基于浏览器的游戏工作,并且完全是关于速度速度的。

于 2012-12-08T13:02:57.797 回答
0

这是最新的样板https://github.com/techlab/jquery-plugin-boilerplate

您还可以使用create-jquery-plugin npm CLI 实用程序。赶紧跑

npx create-jquery-plugin
于 2020-07-21T16:40:57.110 回答