Namespacing in jQuery?
I am currently working on a library plugin for jQuery that might eventually be released as an open source project.
I have written a number of custom element functions and would like to store everything related to my library in a namespace.
So for example, assume that I have a function called toggle()
. Ordinarily, this would be called using $(selector).toggle()
. However, I would like to call it, and other functions using something like $(selector).mylib.toggle()
so as not to interfere with other libraries or plugins.
I have developed jQuery plugins in the past, but nev开发者_Python百科er needed to protect methods in this way. Can anyone point me in the direction of how I might author the functions to achieve this?
I'm not exactly sure, why you would want to do this and not use an "ordinary" namespace object which holds your methods. However, you might want to have a look at
jQuery.sub()
Description: Creates a new copy of jQuery whose properties and methods can be modified without affecting the original jQuery object.
By "sub"(classing) the jQuery object, you don't have to care about conflicting with other plugins anymore. So if that is the only concern, go for it.
Ref.: .sub()
精彩评论