jQuery插件-初始化后更新设置

jQuery plugin - update settings after initialization

本文关键字:更新 设置 初始化 插件 jQuery      更新时间:2023-09-26

我有一个jQuery插件,我希望能够随时更改选项,比如这个例子:$('.element').pwstabs('options','effect',scale)或类似的东西。我尝试添加update: function,尝试添加Plugin.prototype.update,但仍然不知道如何做到这一点:)

以下是插件的结构:

    ;(function ($, window, document, undefined) {
  var pluginName = "pwstabs",
    defaults = {
      effect: 'scaleout',
      defaultTab: 1,                
      containerWidth: '100%',       
      tabsPosition: 'horizontal',   
      horizontalPosition: 'top',    
      verticalPosition: 'left',     
      responsive: false,            
      theme: '',                    
      rtl: false,                   
      controlls: false,
      next: '',
      prev: '',
      first: '',
      last: '',
      auto: false,
      play: '',
      pause: ''
    };

  function Plugin(element, options) {
    this.element = $(element);
    this.$elem = $(this.element);
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }
  Plugin.prototype = {
    init: function(){
      // Here's the code for the plugin
    }
  };
  $.fn[pluginName] = function ( options ) {
    return this.each(function () {
      new Plugin( this, options );
    });
  };
})(jQuery, window, document);

所以现在我使用的插件是:

$('.element').pwstabs({
  effect: 'scalein',
  defaultTab: 2
});

当我点击一个按钮时,我想把效果改为scaleout。代码类似:

$('.button').click(function(){
  $('.element').pwstabs('options','effect','scalein');
});

那么我该如何在插件中实现这一点呢?

当前该插件中唯一支持的调用模式是发送一个包含覆盖默认设置的对象文字。例如:

$('.element').pwstabs({
  effect: 'scalein',
  defaultTab: 2
});

该调用模式在以下方法中定义:

$.fn[pluginName] = function ( options ) {
    return this.each(function () {
        new Plugin( this, options );
    });
};

正如您所看到的,一个选项字典作为唯一的参数发送到构造函数Plugin()以构建插件并初始化它。

为了支持所需的调用模式,您必须修改此方法以支持两种调用模式(使用对象文字初始化,但也调用任何具有更多参数的方法,如选项设置方法)。

这里有一个改进的函数,它将处理这两种调用模式。此外,它还将插件的实例存储在元素上,因此您可以在同一元素的后续调用(例如设置更改)中访问现有设置等。

$.fn[pluginName] = function (options) {
    // get the arguments 
    var args = $.makeArray(arguments),
        after = args.slice(1);
    return this.each(function () {
        // check if there is an existing instance related to element
        var instance = $.data(this, pluginName);
        if (instance) {
            if (instance[options]) {
                instance[options].apply(instance, after);
            } else {
                $.error('Method ' + options + ' does not exist on Plugin');
            }
        } else {
            // create the plugin
            var plugin = new Plugin(this, options);
            // Store the plugin instance on the element
            $.data(this, pluginName, plugin);
            return plugin;
        }
    });
}

这将允许您根据请求调用插件:

$('.element').pwstabs('options','effect','slidedown');

然而,这意味着你在插件原型中有一个"选项"方法,所以一定要添加一个:

Plugin.prototype = {
    options: function (option, val) {
        this.settings[option] = val;
    },
    // Constructing Tabs Plugin
    init: function () {
        // omitted code for brevity
    }
}

如您所见,选项设置只是在现有实例上设置新选项。非常简单高效。新设置将由点击方法处理程序获取,瞧!

以下是一个jsFiddle,其中包含示例代码,以防您在实现我目前所描述的内容时遇到困难:

http://jsfiddle.net/7whs3u1n/6/

更新:我已经大大改进了我的答案,去掉了不需要的东西,包括更多的细节和有效的完整实现(检查上面的fiddle);)我希望这能回答你的问题!

为插件添加状态性并不困难,但当你有空闲时间时,也可以检查写有状态jQuery有状态插件的替代机制,称为jQuery窗口小部件工厂:

http://learn.jquery.com/plugins/stateful-plugins-with-widget-factory/

将来,您可以考虑重写插件以使用小部件工厂。这肯定会让你的代码更简单;)

尝试此模式

(function ($) {
    var defaults = {
        "text": "abcdefg",
    }
    , options = $.extend({}, defaults, options);
    $.fn.plugin = function (options) {
        var options = (function (opts, def) {
            var _opts = {};
            if (typeof opts[0] !== "object") {
                _opts[opts[0]] = opts[1];
            };
            return opts.length === 0 
                   ? def 
                   : typeof opts[0] === "object" 
                     ? opts[0] : _opts
        }([].slice.call(arguments), defaults));
        return $(this).text(options.text)
    }
}(jQuery));
$(".results:eq(0)").plugin(); // return `defaults`
$(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
$(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`

    (function ($) {
        var defaults = {
            "text": "abcdefg",
        }
        , options = $.extend({}, defaults, options);
        $.fn.plugin = function (options) {
            var options = (function (opts, def) {
                var _opts = {};
                if (typeof opts[0] !== "object") {
                    _opts[opts[0]] = opts[1];
                };
                return opts.length === 0 
                       ? def 
                       : typeof opts[0] === "object" 
                         ? opts[0] : _opts
            }([].slice.call(arguments), defaults));
            return $(this).text(options.text)
        }
    }(jQuery));
    
    $(".results:eq(0)").plugin(); // return `defaults`
    $(".results:eq(1)").plugin({"text":"gfedcba"}); // return `options`
    $(".results:eq(2)").plugin("text", 123); // return `arguments` as `options`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="results"></div><br />
<div class="results"></div><br />
<div class="results"></div>