frictionlesspulley
frictionlesspulley

Reputation: 12358

extending jquery with a generic function

I am writing the a generic function for my website using jquery which would be used over the entire site for displaying a success/error message. I decided to make it a plugin.

A simple form of the plugin is given below:

; (function ($) {
        jQuery.FlashMessage=function(msg){
            alert(msg);
        }

})(jQuery);

I wanted to know whether it is a good practice to define plugins in the jquery namespace or should it defined under $.fn.XXXX ..or am i overthinking and it doesn't matter it at all.

Upvotes: 1

Views: 2331

Answers (3)

Praveen Prasad
Praveen Prasad

Reputation: 32107

jQuery.fn is equivalent to jQuery.prototype

with jQuery.fn.FlashMessage you can do

 jQuery.fn.FlashMessage=function(){
    return this.each(function(){
        //do some thing
    });
  });


//use like this, your chaining is secured    
jQuery('#someElement').FlashMessage().DoSomeThingElse().SomethingMore();

if you are concerned is modifying only one element than why to use jQuery.FlashMessage, do it like myNameSpace.FlashMessage

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816334

You add those functions to jQuery.fn which should be run on selected elements, e.g. $('div').yourFunction().

If you want a "generic" function, like $.ajax(), then you should add it to the jQuery object, like you already do. But I would use $ inside the function:

(function ($) {
        $.FlashMessage=function(msg){
            alert(msg);
        }

})(jQuery);

So it depends on what kind of functionality you want.

Upvotes: 4

Bryan Downing
Bryan Downing

Reputation: 15472

Typically plugins on the fn namspace return a jQuery object to maintain chainability. Also they are applied to jQuery.prototype so all jQuery objects can call it.

Check out this page for a very good overview on plugin authoring: http://docs.jquery.com/Plugins/Authoring

Upvotes: 0

Related Questions