views:

715

answers:

2

I am creating a form validation plugin for jQuery and would like it to call a function once the form has been successfully validated. The plugin will have a default callback function, but I would like to modify this through the options parameter. Unfortunately what i have (below) does not work. Any ideas?

(function($){
    $.fn.extend({
        validify : function(options) {
            var defaults = {
                callback: "callbackFunc",
            };

            var options = $.extend(defaults,options);

            return this.each(function(){
                //validation code here
                //if valid call the function
                if(errors==0){
                    options.callback;
                }


            function callBackFunc(){
                // the default callback function
            }

            ...
+5  A: 

Remove the quotes and you're golden.

This will pass a function reference. You can then call it by doing options.callback();

You will also need to declare the function before you pass the reference along. You could get around this by doing this instead:

callback: function() { callbackFunc(); }
Paolo Bergantino
If i remove the quotes i get a js error:callbackFunc is not defined[Break on this error] callback: callbackFunc
Neil Mills
you need to define the function ABOVE the place where you reference it
joshng
What he said. :)
Paolo Bergantino
See my edited, complete answer below ;-)
joshng
+1  A: 

Pass the function itself, rather than its name (ie, remove the quotes):

(function($){
    function callBackFunc(){
      // the default callback function
    }

    $.fn.extend({
        validify : function(options) {
            var defaults = {
                callback: callbackFunc // IMPORTANT: remove quotes AND trailing comma
            };

            var options = $.extend(defaults,options);

            return this.each(function(){
                //validation code here
                //if valid call the function
                if(errors==0){
                    options.callback();  // note parentheses
                }

            ...
joshng