简体   繁体   English

将配置对象传递给jQuery插件

[英]Passing a configuration object to a jQuery plugin

I often use the below design pattern to create jQuery plugins. 我经常使用下面的设计模式来创建jQuery插件。 I specify default values in the plugin, and allow the user to change them when they initialize the plugin. 我在插件中指定默认值,并允许用户在初始化插件时更改它们。 Normally, my default object just contains string properties, not objects, but this time, I wish to make one of the default properties an object ( default_obj_1 in my example). 通常,我的default对象仅包含字符串属性,而不包含对象,但是这次,我希望将默认属性之一作为对象(在我的示例中为default_obj_1 )。 At the bottom of the script, you see me attempt to change one of the properties of by passing the plugin {default_value_2: 666, default_obj_1.default_prop_3: 434} , but it invalid JavaScript and errors out. 在脚本的底部,您看到我尝试通过传递插件{default_value_2: 666, default_obj_1.default_prop_3: 434}来更改的属性之一,但是它无效了JavaScript并且出错了。 I also tried passing it {default_value_2: 666, default_obj_1: {default_prop_3: 434} but it appears to overwrite the other values which should remain. 我还尝试传递它{default_value_2: 666, default_obj_1: {default_prop_3: 434}但它似乎覆盖了应保留的其他值。

How do I update just one of the default values in the jQuery plugin? 如何仅更新jQuery插件中的默认值之一?

(function($){
    var defaults = {
        default_value_1 : 123,
        default_value_2 : 321,
        default_value_3 : 111,
        default_obj_1   : {
            default_prop_1  : 444,
            default_prop_2  : 534,
            default_prop_3  : 231
        }
    };

    var methods = {
        init : function (options) {
            var settings = $.extend({}, defaults, options);
            return this.each(function () {
                //Do something using settings
            });
        }
    };

    $.fn.myPlugin = 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 jQuery.myPlugin' );
        }    
    };

    }(jQuery));

$(function(){

    var myPlugin=$('#elem').myPlugin({default_value_2:666,default_obj_1.default_prop_3:434});

    var myPlugin=$('#elem').myPlugin({default_value_2:666,default_obj_1:{default_prop_3:434} });

});

Change: 更改:

var settings = $.extend({}, defaults, options);

to

var settings = $.extend(true, {}, defaults, options); // notice the first param TRUE

to do a deep (recursive) merge. 进行深度(递归)合并。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM