Posts Tagged ‘ mootools ’


This is how easy it is to avoid javascript conflicts with mootools or prototype or whatever.  Just put
all your logic into a private scoped function … it can have its own variables, other functions, event handlers, etc.
It can talk to all the same DOM elements any other javascript library can.
Using the $ Alias Without Creating Global Conflicts

Problem

You want to use the shortcut $ alias instead of typing the global namespace name
(jQuery) without fear of global conflicts.

Solution

The solution here is to create an anonymous self-invoking function that we pass the
jQuery object to and then use the $ character as a parameter pointer to the jQuery
object.

For example, all jQuery code could be encapsulated inside the following self-invoking
function:

(function($) { //function to create private scope with $ parameter
//private scope and using $ without worry of conflict
$.someJQueryFunction();
$(‘td’).doSomethingToAllTDElements(function() {
});
//
})(jQuery); //invoke nameless function and pass it the jQuery object

It really looks like this:

(function($) { } )(jQuery);

an example of something similar:

(function(someVar) {
alert(“someVar = ” + someVar);
})(“blah”);

would trigger an alert saying: someVar = blah

Discussion

Essentially, what is going on here is that we have passed the global reference to jQuery
to a function that creates a private scope. Had we not done this and chosen to use the
shorthand $ alias in the global scope, we would be taking a risk by assuming that no
other scripts included in the HTML document (or scripts included in the future) use
the $ character.

Why risk it when you can just create your own private scope?

Another advantage to doing this is that code included inside of the anonymous selfinvoking
function will run in its own private scope. You can rest assured that anything
that is placed inside the function will likely never cause a conflict with other JavaScript
code written in the global scope. So, again, why risk programmatic collisions? Just
create your own private scope.

Tags: , , ,