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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With