Nordin Nordin - 1 year ago 118
Javascript Question

Unify $ function of Prototype and JQuery

Is there any JavaScript function that can unify $ function from both Prototype and jQuery?

Yes, this is the real use case I am facing now. I find $ function in Prototype and $ in jQuery is conflicting each other. I know that we could us jQuery.noConflict() to ressign $ back to Prototype, however by doing so, I will have to rewrite jquery-specific javacript code that use that $ function, or have jquery specific in a code block (eg. anonymous function).

Is there any easier way, without having to rewrite existing code in both library and have them in one page?

The code that could answer this question may look like this, and your feedback is greatly appreciated:

<script type="text/javascript" src="/path/to/prototype.js"></script>
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var $j = jQuery.noConflict();
var $p = $; // reference to prototype's $
var $ = function(E, F){
var isJQuery = true;

//TODO: logic to determine which $ to use here YOUR SUGGESTION HERE ;-)

var result = null;
result = $j(E, F);
} else { // prototype
//TODO: code to delegate prototype $

return result;
/* ]]>*/

// ... any existing javacode jQuery and Prototype using $ function.


update: Rewrite question to be more clear.

Answer Source

Well, first of all, I can rarely find usefull cases where both of the libraries have to be included in the same page. So you might consider to remove one.
I guess that this is due to a plug-in use, but have a look at the opponent plug-in list, I'm quite sure that there is an alternative.

Second, for your jQuery specific code, it's quite easy to rewrite it, using the anonymous function trick:

  ... your code here ...

This will work in most of the cases where you don't put global variables or methods rather than binding them to events.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download