1

I'm coding my own jQuery plugin, based on http://docs.jquery.com/Plugins/Authoring

(function($)
{
    var methods = 
    {
        publish : function(options) 
        {
            var settings = 
            {
                title : 'Publish'
            }
            var obj = $(this);
            var opt = $.extend(settings, options);
            return this.each(function() 
            {
                //some code here
            });
        }
    };

    $.modal = function(method) 
    {
        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');
        }  
  };

})(jQuery);

Now the problem is if I don't use: $.fn.modal = function(method)... An error shows: Too much recursion. I want to use: $.modal so then I can call it like: $.modal(); How can I use a lot of methods with their own options and without element like $(element)?

Thanks

2 Answers 2

2

Solved using:

(function($)
{
    var methods = 
    {
        publish : function(options) 
        {
            var settings = 
            {
                title : 'Publish'
            }
            var opt = $.extend(settings, options);
            //some code here
        }
    };

    jQuery.extend(function(){
        modal : function(method) 
        {
            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');
            }  
      };
    });

})(jQuery);

Now I can use: $.modal(method, options);

Sign up to request clarification or add additional context in comments.

Comments

0

What you are doing is not wrong, the problem is, that if you append directly to the jQuery object and not to jQuery.fn the this reference will point to the function executed and not the element of $(element) (if you are familiar with OOP think about it as static methods).

So when you use method.apply you are just passing the reference of $.method it changes the pointer of the this reference for the function you are calling. I assume that this is not what you want to do and that this leads to the recursion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.