How can I expand parameters as global in jquery plugin?

I am trying to create a jquery plugin. This is a validation plugin. After submitting the form, I want to submit data using ajax. I am creating a validate constructor and inheriting it as a prototype. But I cannot use the default value outside the jquery namespace.

I want to use the ops variable as a global variable, since I can access it from a javascript prototype. So, I need an effective way to do this.

    (function($){
      $.fn.validation = function(options){
        var ops = $.extend({}, $.fn.validation.defaults, options);   
        //wanna make ops as  global as I can access  from prototype
      };
    }(jQuery));

    $.fn.validation.defaults = {
        url: 'validation.php',
        methodType: 'post',
    };

    function Validate(){               // constructor
      this.error = [];
    }

    Validate.prototype = {

        constructor : Validate,

        submitForm : function(currentForm){
            var formData = new FormData(currentForm);
                $.ajax({
                    url: opt.url,                 //  wanna call like that.
                    type: opt.methodType,        
                    //   Don't wanna use  $.fn.validation.defaults.methodType
                    success: function(data){

                    },
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false
                });
    }

};
+4
source share
2 answers

Define a variable opsunder the jquery object $.opsand return this object from the extended functionjquery $.fn.validation.options

(function($){
   $.ops = {};

   $.fn.validation = function(options){
       $.ops = $.extend({}, $.fn.validation.defaults, options);   
      //wanna make ops as  global as I can access  from prototype
   };
   // expose the ops object to outside world
   $.fn.validation.options = function () {
       return this.ops;
   }
}(jQuery));
+2
source

ops document.ready, global scope, document.ready, local scope, ops local scope.

: , ops , . document.ready , ops undefined.

// Global scope
var ops;

(function($){
  $.fn.validation = function(options){
    /// Local scope
    ops = $.extend({}, $.fn.validation.defaults, options);   
  };
}
+1

Source: https://habr.com/ru/post/1621435/


All Articles