2012-04-03 128 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