Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom jQuery function without selector prerequisite

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').myFunction().

However, for a project I'm currently working on, I need to be able to define a function that does not require a selector to work.This is actually for a MessageBox plugin, which will act in a similar manner to C#'s MessageBox class. As such, I would ideally like to create the function as MessageBox, and then call it as follows:

var myMessage = $.MessageBox(); and then in turn myMessage.Show();

Notice the lack of selector brakets in the jQuery reference at the beginning of the function call.

Any advice on the best practice for this would be gratefully received.

like image 375
BenM Avatar asked Apr 23 '11 12:04

BenM


2 Answers

This should work:

jQuery.MessageBox = function() {
  var show = function() {
    // something...
  }
  var hide = function() {
    // something...
  }
  return {
    show: show,
    hide: hide
  }
}
like image 153
Amadan Avatar answered Oct 05 '22 12:10

Amadan


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()
like image 34
TheStoryCoder Avatar answered Oct 05 '22 11:10

TheStoryCoder