Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this port of Prototype to JQuery correct?

We have code that will run if the user is idle for a certain amount of time. (doStuff resets a countdown)

Existing code in Prototype:

Event.observe(window, 'mousemove', function() { doStuff(); });
Event.observe(window, 'scroll', function() { doStuff(); });
Event.observe(window, 'click', function() { doStuff(); });
Event.observe(window, 'focus', function() { doStuff(); });
Event.observe(window, 'blur', function() { doStuff(); });
Event.observe(window, 'keypress', function() { doStuff(); });

Event.observe(document, 'mousemove', function() { doStuff(); });
Event.observe(document, 'scroll', function() { doStuff(); });
Event.observe(document, 'click', function() { doStuff(); });
Event.observe(document, 'focus', function() { doStuff(); });
Event.observe(document, 'blur', function() { doStuff(); });
Event.observe(document, 'keypress', function() { doStuff(); });

I am looking to replace it with this JQuery:

 $(document).ready(function() {
     $(document).bind("mousemove scroll click focus blur keypress", doStuff);
 });

It checks out when I test it, but can anyone confirm I don't have to do the document/window check, or that I didn't overlook anything else? Thanks.

like image 429
blu Avatar asked Feb 09 '10 22:02

blu


2 Answers

Close, this is a complete port (added window) and the Document ready test isn't needed:

 $([document, window]).bind("mousemove scroll click focus blur keypress", doStuff);

You can pass an array to the jQuery function so what you set up applies to more than one item. In this case, you already have references to window and document. This is how you can do it in one call.

However, I don't think all the original Prototype code was needed. For instance, focus and blur dont' apply to the document and click, mousemove and keypress isn't needed on the window.

This might be more what you want:

$(window).bind("focus blur scroll", doStuff);
$(document).bind("click mousemove keypress scroll", doStuff);

DOM Ready not needed: The DOM ready test is not needed because you already have access to document and window immediately. Waiting for DOM ready is needless.

like image 183
Doug Neiner Avatar answered Nov 14 '22 01:11

Doug Neiner


That Prototype code is...non-optimal to say the least, and not for any reason related to Prototype.

Your rewrite looks fine other than that you've dropped window. If not hooking the events on window is valid in jQuery, it's valid in Prototype.

A similar rewrite in Prototype making similar assumptions (but including window):

$w('mousemove scroll click focus blur keypress').each(function(evtname) {
    document.observe(evtname, doStuff);
    Event.observe(window, evtname, doStuff);
});

...and I wouldn't be surprised to find that even that's more verbose than it actually needs to be.

like image 1
T.J. Crowder Avatar answered Nov 14 '22 01:11

T.J. Crowder