全局定义jQuery插件参数 [英] Globally defining jQuery plugin parameters

查看:71
本文介绍了全局定义jQuery插件参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为主题制作一个小插件,如何在一个字符串中声明参数(选项),而不是每次调用该函数时都必须包含它们?该插件必须是一个外部文件,我需要能够在本地更改选项,这就是为什么我需要这种设置.我知道这是错误的,但这是我正在寻找的东西-

I'm making a small plugin for a theme, how do I declare the parameters (options) in one string rather than having to include them each time I call the function? The plugin has to be an external file and I need to be able to change the options locally which is why I need this sort of setup. I know this is wrong but it's the sort of thing I'm looking for -

var options = {minwidth: 250, maxwidth: 500, crazy: 0.6, bigger: 100};

(function($) {
$.fn.rosalind = function(options) {
  return this.each(function() {
    var elm = $(this);
    var width = Math.floor(Math.random()*options.minwidth) + options.maxwidth - options.minwidth;
    var poswidth = $('#shell').width() - width;
    var left = Math.floor(Math.random()*poswidth);
    elm.css({'margin-left': left, 'margin-top': top, 'width': width}).attr('width', width);
    var height = $(this).height();
    var ratio = Math.floor(options.bigger*height/width);
    var wratio = width/options.maxwidth;
    elm.attr({'rel': ratio, 'alt': wratio});
    top += Math.floor(Math.random()*ratio*options.crazy + wratio*ratio/2);
  });
 };
})(jQuery);

$('.post:visible').rosalind();

谢谢

推荐答案

一个选项是从以下样板开始,该样板将使用调用函数的参数扩展一组默认值:

One option is to start with a boilerplate like the following that takes care of extending a set of defaults with the parameters that the function was called with:

// start of anonymous function, no global namespace is used. Formal parameter $ is passed the jQuery object, see closing of function definition.
(function ($) {
    // define default parameters for myPlugin. These can be overridden by the call, or from data attached to the jQuery object
    var defaults = {optionOne: true, optionTwo: 'CALI', callback: function () {/* code here, or leave it out of the defaults so it will be null by default */}};
    // this next line adds myPlugin to the jQuery functions because ".fn" is an alias for "prototype". The function call enables behavior like $("selector").myPlugin('action', {optionOne: false});
    $.fn.myPlugin = function (action, options) {
        var passed = options, // passed will store the options that were passed in. This allows us to see what was sent after the options are expanded with defaults.
            obj, // the jQuery object being worked with -- check to see if this can be handled with "el" locally.
            dataStore, // object to store persistant data for the jQuery objects being worked with.
            result; // used if we are passed a call that requires returning a result rather than returning the jQuery collection we were passed.

        // code here, functions to be called as actions
        function initialize() {} function single() {} function getDual() {} function setDual() {}

        function getOptions(el) {
            var optionsPrior = el.data('myPlugin:options'), // attempt to load prior settings
                dataStorePrior = el.data('myPlugin:data'); // load any stored data

            options = (optionsPrior !== undefined) ? optionsPrior : $.extend(true, {}, defaults, options); // sets options either to prior options or extends the default options with those that were passed in.
            options = $.metadata ? $.extend(true, {}, options, el.metadata()) : options; // check for settings attached to the current object

            if (dataStorePrior !== undefined) { // if there is a prior data store populate the active datastore with it.
                dataStore = dataStorePrior;
            }
        }

        function setOptions(el) {
            el.data('myPlugin:options', options); // store setting to the object
            el.data('myPlugin:data', dataStore); // store datastore to the object
        }

        // check to see if the first parameter passed is an object instead of an string containing an action, if so then use the object as options and set the action to initalize.
        if (!action || typeof (action) === 'object') {
            options = action;
            action = 'initialize';
        }

        // process each element in the jQuery object collection
        this.each(function (el) {

            // store reference to the currently processing jQuery object -- check to see the value of this over using "el" from the function
            var obj = $(this);

            getOptions(obj); // load the current options

            if (action && typeof (action) === 'string') { // this is an alternative to the use of "var methods = {function methodOne ()..." that allows a single action to have both a set and get that can call different functions.
                switch (action) {
                case 'initialize':
                    initialize(obj);
                    break;
                case 'singleOptionAction':
                    single(obj);
                    break;
                case 'dualModeAction':
                    //return and set
                    if (passed === undefined) {
                        result = getDual;
                    } else {
                        setDual(obj, passed);
                    }
                    break;
                default:
                    break; // we have no listed method that matched what they sent
                }
            }
            setOptions(el);
            // code here
        });

        return this; // this enables chaining; without it the jQuery collection that is passed in is not passed further along the chain. Alternatively if you are trying to filter or modify the jQuery collection you'll want to return a modified version of this.
    };
}(jQuery)); // end anonymous function definition and execute it, passing in the jQuery object.  
                // jQuery should already be loaded, and the "$" reference is used only within your function definition, keeping this reference safe from being clobbered by other scripts.
                // After execution, your plugin is defined and ready to use.

有很多编写jQuery插件的方法,此示例仅显示了一组选择.

There are many ways to write a jQuery plugin and this example just shows one set of choices.

这篇关于全局定义jQuery插件参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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