Best practices for JQuery namespaces + general purpose utility functions

前端 未结 2 645
南旧
南旧 2021-01-31 23:26

What are some current \"rules of thumb\" for implementing JQuery namespaces to host general purpose utility functions?

I have a number

相关标签:
2条回答
  • 2021-02-01 00:04

    For the record, I ended up using the first syntax:

    $(function ()
    {
       //********************************
       // PREDIKT NAMESPACE
       //********************************
    
       if (typeof (Predikt) === "undefined")
       {
          Predikt = {};
       }
    
       //********************************
       // PREDIKT.TIMER NAMESPACE
       //********************************
    
       if (typeof (Predikt.Timer) === "undefined")
       {
          Predikt.Timer = {};
       }
    
       Predikt.Timer.StartTimer = function ()
       {
          return new Date().getTime();
       };
    
       Predikt.Timer.EndTimer = function ()
       {
          return new Date().getTime();
       };
    
    });
    
    0 讨论(0)
  • 2021-02-01 00:27

    For jQuery plugins and such the pattern is to use $.fn.myPlugin if you want it to be available on elements, and $.whatever if you just want to use the namespace. I recommend reading the official Plugins Authoring document and these articles.

    But jQuery aside, the easiest way to namespace your utils would be along these lines:

    var utils = window.utils || {};
    utils.method = function(){};
    

    The basics of namespacing in JS hasn't really changed lately - You should check out snook's article, DED's elegant approach and this SO question.

    The main advantage of using a self-invoked function to declare namespaces is you can execute stuff privately before returning the object. Also, the object will be ready for auto-complete by your console, which you'll miss on the $ namespace because jQuery returns a function rather than an object.

    0 讨论(0)
提交回复
热议问题