2012-04-03 88 views
6

继善jQuery Plugins/Authoring说明我有一个小问题jQuery的 - 插件选项默认扩展()

(function($){ 

    // Default Settings 
    var settings = { 
    var1: 50 
    , var2: 100 
    }; 

    var methods = { 
    init : function (options) { 
     console.log(settings); 
     settings = $.extend(options, settings); // Overwrite settings 
     console.log(settings); 
     return this; 
    } 
    , other_func: function() { 
     return this; 
    } 
    }; 

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

})(jQuery); 

如果我做

>>> $('my_element').my_plugin({var3: 60}) 
Before Object { var2=100, var1=50} 
After Object { var3=60, var2=100, var1=50} 
[ my_element ] 

>>> $('my_element').my_plugin({var1: 60}) 
Before Object { var1=50, var2=100} 
After Object { var1=50, var2=100} 
[ my_element ] 

为什么我var1不重写?

回答

19

你混在一起的参数的顺序在$.extend(目标应该是第一个),它应该是:

settings = $.extend(settings, options); 

this fiddledocs for $.extend()

要避免混淆,您还可以使用默认设置扩展您的设置,例如:

methods.init = function(options){ 

    var settings = $.extend({ 
    key1: 'default value for key 1', 
    key2: 'default value for key 2' 
    }, options); // <- if no/undefined options are passed extend will simply return the defaults 

    //here goes the rest 

}; 
+0

确实这是命令,非常感谢你 – 2012-04-03 14:45:08

+1

这帮助我使[我的第一](https://github.com/Glideh/jquery.particles.burst)githubbed jquery插件:) – 2012-04-04 08:43:20

4

您正在覆盖您的默认值。尝试创建一个新变量来存储init方法中的设置。

var defaults = { 
    var1: 50 
    , var2: 100 
    }; 

    var methods = { 
    init : function (options) { 
     console.log(defaults); 
     var settings = $.extend({},defaults,options || {}); 
     console.log(settings); 
     $(this).data("myPluginSettings",settings); 
     return this; 
    } 
    , other_func: function() { 
     console.log(this.data("myPluginSettings")); 
     return this; 
    } 
    }; 
+0

我反转了参数。谢谢 – 2012-04-03 14:45:29