Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing jquery static util methods

Tags:

jquery

I understand the concept of extending the jquery.fn to place your custom functions on the prototype chain of a jquery object, but in my case some of my utils don't need to be attached to a selector. I'm basically looking for a static method. So I wanted to know of any pitfalls of writing static methods directly on the jquery object as util methods.

Example:

jquery.myMethod = function(arg){
   ......
} 

$.myMethod("blabla");

Thanks

like image 749
Chapsterj Avatar asked Sep 24 '11 19:09

Chapsterj


2 Answers

As you seem to realize, it is a good idea to not dump all your utility functions into the global namespace. The less you can impact the global namespace, the better. If you already have jQuery, then your choices for where to put them are:

  1. As new methods on the jQuery object as: jQuery.myUtil1(), jQuery.myUtil2().
  2. As new methods under one object on the jQuery object as: jQuery.jfUtils.myUtil1(), jQuery.jfUtils.myUtil2().
  3. As new methods on one new global object (nothing to do with jQuery) as: jfUtils.myUtil1(), jfUtils.myUtil2().

Option 2) seems better to me than option 1) because you lessen the chance of colliding with other jQuery functions though you do add an extra lookup for each function call.

Option 3) seems perfectly acceptable to me as it only adds one new item to the global namespace so as long as you make the name reasonably unique, you should be OK.

So, I'd think you could go with either option 2) or option 3). Option 2) might be a little safer because you know the general extent of what is in that namespace, but either can work.

like image 97
jfriend00 Avatar answered Nov 01 '22 21:11

jfriend00


You shouldn't add static methods to jQuery. You don't gain anything by trying to. The point of extending jQuery is so that jQuery objects found with query strings will have methods on them. You're simply creating a global function, so just create a new top-level object to hold your functions.

like image 39
Ned Batchelder Avatar answered Nov 01 '22 23:11

Ned Batchelder