2012-04-06 34 views
1

我有一段時間以前寫過的簡單(輕量級)div滑塊,因爲我在各種不同的項目中使用它 - 現在已經到了將它包裝到它自己的插件中的時候了(可能它並不是那麼輕量級了!)。自定義JQuery插件 - 如何獲取/維護用戶定義的選項?

我一直在閱讀,並從http://docs.jquery.com/Plugins/Authoring複製,因爲這是彈出我的插件櫻桃,它是有道理的(主要),但有些東西是逃避我。這裏是我的插件代碼:這裏

(function($) { 

    //List of callable methods 
    var methods = { 
     init : function(options) { 

      var settings = $.extend({ 

       optionOne : 'aaa', 
       optionTwo : 'bbb', 
       optionThree : 'ccc', 
       optionFour : 'ddd' 

      }, options);   

     }, 

     error : function(message) { 
      alert(message);    
     },   

     showSettings : function() { 
      //This bit... how to show whats in 'settings' defined in init? 
     } 

    } 

    $.fn.ccSlider = function(method) { 

     //Calling methods 
     if (methods[method]) { 
      //If plugin is called with a recognised method, run that. 
      return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || !method) { 
      //if plugin is called without a method, run the init() function 
      return methods.init.apply(this, arguments); 
     } else { 
      //Run the error() function to catch all else. 
      return methods.error("ccSlider: Method '"+method+"' does not exist!");    
     } 
    }; 

})(jQuery); 

一切工作正常,但我不能去寫我需要的方法,但這只是因爲我無法弄清楚如何訪問的「設置內容'在init()方法之外。

我正在使用'showSettings'作爲測試...我將如何編寫一個showSettings方法,彈出並告訴我指定設置的值(比如說,optionTwo)是什麼?

+0

..或者最佳實踐,根據JQuery網站... – Codecraft 2012-04-06 19:54:30

回答

1

您的體系結構是正確的,但是方法和設置對於您的插件應該是全局的。

(function($) { 
    var defaults = { 
     optionOne : 'aaa', 
     optionTwo : 'bbb', 
     optionThree : 'ccc', 
     optionFour : 'ddd' 
    } //if there are any 

    var settings = {}; //you can reach the settings from any where in your plugin now 
    //List of callable methods 
    var methods = { 
     init : function(options) { 
     //initialize the settings in your init function and you are good to go 
     settings = $.extend({},defaults,options);   
     }, 

     error : function(message) { 
     alert(message);    
     },   

     showSettings : function() { 
     //This bit... how to show whats in 'settings' defined in init? 
     } 

    } 

    //your plugin code here like in your post but now you can use the settings variable  we defined in your plugin 
}); 
+0

這就是我想的,但我無法得到它的工作。我休息了一會兒,然後回過頭來,順其自然,謝謝:) – Codecraft 2012-04-06 23:58:56