I’ve got an event handler set on document
, listening for submit
and change
events, delegated to any form
elements on the page. The idea is to update the server when an input is altered (since the event bubbles up to the form), while also allowing for submitting an entire form. I have a few overrides in place for inputs that need special handling, and this works great (since they’re placed higher up in the code, I can block the main event handler with .stopImmediatePropagation()
– all these handlers are on document
.)
What I’m trying to do now is intercept the change
event on a specific input, then instead of preventing, I want to re-trigger the primary handler, passing in some additional data (using jQuery’s .trigger(event, [data])
syntax.)
To give a simplified example: http://jsfiddle.net/rrEmq/3/
My goals are to:
- Maintain delegated events (the forms are loaded in dynamically, the JS is loaded once)
- Avoid duplicating code
- Avoid breaking out the main handler’s functionality into separate functions
That third item is my initial approach, and I understand that it will get the job done, but I’d love to find a way to solve this without rewriting the main handler. Obviously, the real kicker is that, since everything’s delegated to the same element, and since I’m using e.target
, I can’t simply trigger a handler higher up in the DOM tree.
Advertisement
Answer
Create a custom event and trigger with the extra data
Instead of
$(this).trigger("change", data);
Call
$(this).trigger("changemodified", data);
And create a handler for this event.
You can reuse handlers
var handleChange = function(e) { }; $("something").on("change", handleChange); $("something").on("changemodified", handleChange);