2012-04-06 35 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