Search code examples
jqueryjquery-pluginschainingjquery-chaining

How to access the one of the chained functions in a plugin?


How can I access the one of the chained functions in a plugin?

this is my plugin, in which I need to return an appended element on the document.

(function($){

        $.fn.extend({ 

            selection: function(options) {

                var defaults = {
                    element:     "selection"
                }

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

                var $this = this;


               $this.function_1 = function(object)
                {
                    alert('function 1');

                }

                $this.function_2 = function(object)
                {
                    alert('function 2');
                }

                $(document.body).append("<div class='element'>Loading</div>");

                var element = $('.element');

                return element;

            }
        });

    })(jQuery);​

It should alerts 'function 2' when the button is clicked but it returns error on firefox.

Below is my jsffiddle,

http://jsfiddle.net/dm3ft/


Solution

  • One approach is to add an argument to the plugin function to pass method as string. Basics are taken from jQuery plugin authoring docs:

    (function($) {
    
        var methods = {
            function_1: function(object) {
                alert('function 1');
            },
            function_2: function(object) {
                alert('function 2');
            }
        };
    
    
    $.fn.selection = function(method, options) {
    
        return this.each(function(){
    
            $(this).click(function() {
    
                  // Method calling logic
                   if (methods[method]) {
                       return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
                   } else if (typeof method === 'object' || !method) {
                       return methods.init.apply(this, arguments);
                   } else {
                       $.error('Method ' + method + ' does not exist on jQuery.tooltip');
                   }
              });
        });
    
    })(jQuery);
    

    Then to call plugin method:

      $('.chain-function').selection('function_2'/* optional options object*/);
    

    DEMO: http://jsfiddle.net/dm3ft/1/

    NOTE: It is important that you realize that this inside the plugin function is the DOM element and not confuse it with this being part of your class