Search code examples
javascriptjqueryprototypejs

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.


Solution

  • 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.