开发者

extending jquery with a generic function

开发者 https://www.devze.com 2023-02-16 05:54 出处:网络
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 plug开发者_如何学Cin.

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 plug开发者_如何学Cin.

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.


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消