jQuery插件 - 初始化后更新设置 [英] jQuery plugin - update settings after initialization

查看:349
本文介绍了jQuery插件 - 初始化后更新设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery插件,我希望能够动态更改选项,例如: $('。element')。pwstabs('options','effect',比例)或类似的东西。我尝试添加 update:function ,尝试添加 Plugin.prototype.update ,但仍然无法弄清楚如何做到这一点:)

I have a jQuery plugin, and I want to be able to change options on the fly, like this example: $('.element').pwstabs('options','effect',scale) or something simular to it. I tried adding update: function, tried adding Plugin.prototype.update, but still cant figure out how to do that :)

以下是插件的结构:

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

现在我使用的插件如下:

So now I use the plugin like:

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

当我点击一个按钮时,我想改变效果让我们说 scaleout 。使用以下代码:

And when I click a button, i want to change effect to lets say scaleout. With code like:

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

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

So how do I implement this in the plugin?

推荐答案

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

Currently the only supported invocation pattern in that plugin is to send in an object literal containing the settings to overwrite the defaults. E.g.:

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

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

That invocation pattern is defined in the following method:

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

如您所见,选项字典作为唯一参数发送给构造函数插件()来构建插件并初始化它。

As you see, a dictionary of options is sent as the only parameter to the constructor function Plugin() to build the plugin and initialize it.

要支持您需要的调用模式,您必须修改此方法以支持两种调用模式(使用对象文字进行初始化,但是也可以调用任何带有更多参数的方法,比如你的选项设置方法)。

To support the invocation pattern you need, you would have to modify this method to support both invocation patterns (initialization with an object literal, but also invoking any method with more params, like your options setting method).

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

Here is an improved function that will handle both invocation patterns. In addition it will also store the instance of a plugin on an element, so you can access the existing settings etc. on subsequent invocations (e.g. settings changes) on the same element.

$.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;
        }
    });
}

这将允许您按要求调用插件:

This would allow you to invoke the plugin as requested:

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

但是,这意味着你在Plugin原型中有一个'options'方法,所以一定要添加一个:

However, this implies you have an 'options' method in the Plugin prototype, so make sure to add one:

Plugin.prototype = {

    options: function (option, val) {
        this.settings[option] = val;
    },

    // Constructing Tabs Plugin
    init: function () {
        // omitted code for brevity
    }
}

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

As you see the options settings just sets the new option on the existing instance. Very simple and efficient. The new setting will be picked up by the click method handler and voila!

这是一个带有示例代码的jsFiddle,以防您在实现我目前所描述的内容时遇到问题:

Here is a jsFiddle with example code in case you have trouble implementing what i was describing so far:

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

更新:我已经大大改进了我的答案,以摆脱不必要的东西,包括更多的细节和完整的实施,工作(检查上面的小提琴);)我希望这回答你的问题!

Update: I have much improved my answer to get rid of unneeded stuff, include more details and a full implementation that works (check the fiddle above) ;) i hope that this answers your question!

为插件添加状态并不难,但是当你有空闲时间时还要检查编写有状态jQuery有状态插件的替代机制,名为 jQuery widget factory

Adding statefulness to your plugin wasn't hard, but when you have spare time also check the alternative mechanism for writing stateful jQuery stateful plugins called jQuery widget factory:

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

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

In the future you can consider rewriting your plugin to use the widget factory. It would certainly make your code simpler ;)

这篇关于jQuery插件 - 初始化后更新设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆