Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Plugin Defaults and Options

How can I turn the following properties / variables in my plugin into defaults and options that can be set from document ready?

// plugin js:

(function($){
   $.fn.myPlugin = function(options){
      var myForm = this;
      myForm.variable1 = true;
      myForm.variable2 = true;
      myForm.variable3 = true;
      myForm.variable4 = true;

      ...

      if(myForm.variable1){
         // do something
      }

      ...
   }
})(jQuery);

// document ready in page:

<script type="text/javascript">
   $(document).ready(function() {
      $('#form1').myPlugin();
   });
</script>
like image 911
user582065 Avatar asked Jan 18 '12 05:01

user582065


1 Answers

The simplest pattern is to extend a default options object. But it does mean that any parameters have to be passed together as an "option" object, eg: myPlugin({variable2:false})

(function($){
   $.fn.myPlugin = function(options){

      var defaults = {
          variable1 : true,
          variable2 : true,
          variable3 : true,
          variable4 : true
      }

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

      if(settings.variable1){
         // do something
      }

      ...
   }
})(jQuery);
like image 114
Sinetheta Avatar answered Sep 27 '22 19:09

Sinetheta