Namespacing in jQuery? - javascript

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 never 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()

Related

lodash bind function using as jQuery eventHandler... is it possible?

I'm new to lo-dash, and wanted to know is it possible to use _.bind as $.bind and how can I accomplish this? I really want to get rid of jQuery and use something smaller...
What I need is to bind DOM events to functions
Those are two different mechanisms.
_.bind sets the this value of a function to the first parameter so that 'this' will always point to the same object in the function. I'd say it binds the scope of 'this' to the function, except that would be incorrect technically.
$.bind adds a jquery triggered event listener to a jquery wrapped element.
There are plenty of dom selection alternatives (such as zepto.js), but lodash/underscore libraries are really in addition to jquery, not in lieu of jquery.
That being said, this may not necessarily answer your question, except to say zeptoJs might be one such alternative. Again, Underscore/Lodash is not an alternative to but one or the other provides additional functionality (that in the long term will save file size.)
fwiw imho. 37k is not a valid arguments against jquery/lodash and other such tools. why?
1) If you serve your libraries from a cdn its not even a valid hit against the server.
2) These libraries help you write WAY SMALLER code.
In fact this claim sounds more like an excuse than a reason.
cheers.

Is there any benefit to defining a utility function directly on the jQuery object?

Are there any specific benefits derived from defining a utility function directly on the jQuery object:
For instance, given the following two constructs:
$.someUtility = function(){
//do some something with jQuery
}
var someUtility = function(){
//do some something with jQuery
}
Is there any specific reason I would want to use the first example over the second?
Quick Update:
I don't need to do any chaining, and my utility is not a plugin in the traditional sense; It will not perform any operations on a jQuery selector.
You're simply borrowing the global jQuery function object to make your function available to other scripts without further polluting the global variable environment.
If you have no other scripts that rely on that function, you could make it a local variable with no disadvantage except that you'd be polluting your local variable environment.
If you're strictly writing a utility function as opposed to a wrapper method I think the main benefit would simply be that your coding style would be more consistent. A consistent style could be important to you if you plan on using the function on more than a single page.
Three good reasons can be found for choosing to append functions directly on the JQuery object:
you want to build a JQuery plugin (most obvious reason)
the function you are programming applies to DOM nodes, so it could be directly applied to the DOM nodes returned by a JQuery query (sorry for the rhyme)
to keep consistency throughout your code, as you will be lead to use the $ object
Use $.fn.someUtility.
Basically, the first option is creating a jQuery plugin. This allows for your code to be easily reusable in the jQuery context. Inside a jQuery plugin, the this identifier points to the element that was selected in the jQuery selector, allowing for more flexibility when manipulating elements.
I guess the answer to your question is that it really depends. Are you using your function in multiple places?
See JQuery Plugins for more information.
The reason is that your function can then operate on arrays of jQuery-wrapped objects without jumping through the usual hoops. Also in the context of your function, this becomes a reference to the jQuery object on which your function was invoked.
EDIT
My answer assumed defining your function under $.fn.func.
Unless you require access to jQuery selected elements, the only benefit I can see would be by defining under $.func is that you avoid name collisions with other functions defined in the global scope. (As mentioned in my comment below.)
If your utility function uses jQuery (and thus requires it's presence), then I'd say you can use their namespace and put it under $.fn.myUtility as others have recommended. If your utility function is entirely independent of jQuery and does not use it at all and you are likely to have other such utility functions to go with it, then I would tend to make my own global namespace and put your function there such as JLF.myUtility. This makes your code a little easier to reuse in the future even in non-jQuery project.
For me, jQuery gets a lot of it's flexibility and power from the "daisy chain" setup, since every plugin returns "this" you can always call another plugin immediately after, not to mention you are extending an already powerful tool, and that seems like a good idea:)

modify insertBefore

Is there any way that I can replace the insertBefore and similar with my own functions. My aim is to implement an undo feature and if I'm able to implement it this way, I wont have to change each instance of insertBefore in my code with my function name and it would also make the further development easier.
I've found something similar here Disable a built-in function in javascript (alert) but am not able to figure out how to use it in my case because I dont know who is the parent of these functions (insertBefore,appendChild etc).
I just want to insert one line of my code and then call the native code.
Please advise
PS. I'm trying to implement an undo functionality and this library requires me to register an undo in that undo-function for allowing redo. So all I want to do is make that a single line of code is always executed before any insertBefore and similar functions.
I'm not talking about any libraries, but just the plain ECMAscript.
If you are talking about the insertBefore method of the Node interface, then whether you can or can't do is really moot. The important thing is that you shouldn't. It is a method of a host object and should be left alone.
Incidentally, the term built-in is normally used for the built-in objects and methods of ECMAScript. The window.alert method is more correctly described as a method of a host object and really shouldn't be tampered with either (although in general it can be).

Why build Javascript functions as jQuery plugins?

I've seen alot of jQuery implementations of existent JavaScript functions that merely wrap the JavaScript code in a jQuery wrapper and don't actually rely on any of jQuery's base for their operation.
What are the benefits of using Javascript as a jQuery plugin?
If there are none is there a speed loss to use a jQuery plugin that could have easily been implemented outside the wrapper just as well?
Many thanks in advance (just trying to learn something here).
Updated with example:
http://plugins.jquery.com/project/base64
was originally
http://www.webtoolkit.info/javascript-base64.html
Much of jQuery is just a clever wrapper around existing JavaScript functions. $('#some-element') is perhaps a little easier to type than document.getElementById('some-element') but is otherwise not much different.
(I exaggerate, but only slightly.)
The main utility of jQuery is being able to combine together its various components. If I can select elements with a jQuery selector and then perform some action on those elements directly through a jQuery function, that's preferable to having to extract the underlying DOM elements and manipulate them manually, for example.
So it really depends on what functions you're seeing get wrapped. Some of them might very well add no value, and the authors are simply accustomed to everything being in jQuery. (We definitely see that phenomenon on StackOverflow — people who can't find a standard JavaScript function simply because it's not in the jQuery documentation). In other cases, there might be some hidden benefit even if the wrapper does little if anything to modify the underlying function's behavior.
There's also a lot of momentum around jQuery, and general trust. Including arbitrary javascript in your code base may not be as 'acceptable' to higher-up-types as including a new jQuery plugin.
So it may be a mistaken perception, but by being a jQuery plugin, a library benefits by being associated with high quality code.
IMHO the only reason to create a plugin is to execute some functionality against a selector ie a set of selected elements eg
$('.myelements').someFunction();
If your plugin ends up looking like this (case in point the newly released Microsoft Globalisation plugin)
$.doSomeStuff();
then there isnt much benefit that couldn't be gained from using a closure. However a lot of developers dont understand closures and namespaces in javascript, and by following a plugin development templatethey can get the benefit without fully understanding the pattern.

Is it possible to mix MooTools with Prototype and JQuery UI?

There are some things accross these which I'd like to use. I hope they've choosen clever naming conventions to prevent collisions with all their functions and classes? Does anyone use all these at once in one site?
Whilst it can be done (with noConflict), there are still potential conflicts.
For example jQuery adds a unique ID to element nodes it touches, which it expects to manage. If you remove such elements through a means other than jQuery you can get a memory leak; if you clone them from another framework (or DOM calls), you can confuse jQuery with subtle and weird results. There are also many potential interactions between the event models of the frameworks, especially live in jQuery.
If you keep the elements touched by each framework entirely separate, you might be able to get away with it. But really, I wouldn't recommend it. If at all possible, keep the number of frameworks used by your pages between zero and one.
It is possible to use mootools and jquery together, or jquery and prototype together simply by using jQuery.noConflict(). Using all three together might be a stretch as I don't believe that Prototype and Mootools have a no conflict mode and both define $. However, there is this article that talks about using $ safely in Mootools, which might be able to solve your problems.
Mootools and Prototype both extend native javascript objects such as String and Array. I don't think there is any way you can make both of them work together without some conflict.
However, jQuery defines only a single global $ object which it can let go if you use the noConflict mode. You'd then be using the jQuery object.

Categories

Resources