Creating custom jQuery function without selector prerequisite

后端 未结 3 1410
天涯浪人
天涯浪人 2020-12-30 06:00

I know that I can create custom jQuery plugins by using the $.fn.myFunction constructor, and the calling the custom function in JavaScript as $(\'selector

相关标签:
3条回答
  • 2020-12-30 06:26

    relipse has a good point - as you are cluttering the main namespace. A solution if you have more objects than just eg. MessageBox is to create your own namespace like this:

    jQuery.myLib = {
      MessageBox: function() {
        var show = function() {
          // something...
        }
        var hide = function() {
          // something...
        }
        return {
          show: show,
          hide: hide
        }
      }
    }
    

    That means you are only taking one place in the main namespace (the name of your library, in this case myLib). You'd call it like this:

    jQuery.myLib.MessageBox.show()
    
    0 讨论(0)
  • 2020-12-30 06:26
    (function ($) {
        $.MessageBox = function () {
            var show = function () {
                // something...
            }
            var hide = function () {
                // something...
            }
            return {
                show: show,
                hide: hide
            }
        }
    })(Jquery);
    

    I think you better scope to Immediate invocation function to avoid collision with namespaces.

    0 讨论(0)
  • 2020-12-30 06:27

    This should work:

    jQuery.MessageBox = function() {
      var show = function() {
        // something...
      }
      var hide = function() {
        // something...
      }
      return {
        show: show,
        hide: hide
      }
    }
    
    0 讨论(0)
提交回复
热议问题