I've been trying to deal with a lot of duplicate code in the first web pages I've been working on and have been playing around with the prototype model, which I think is the 'right' way to go about it.
What I'm not sure about however is if this is the right way to re-use event handlers. For example:
function GeneralPageHandler(args) {
this.args = args;
this.eventHandlers();
}
GeneralPageHandler.prototype.eventHandlers = function() {
$('#OK').click(function() {
//Do something
});
}
function SpecificPageHandler(args) {
this.args = args;
this.prototype = Object.create(GeneralPageHandler.prototype);
this.prototype.constructor = GeneralPageHandler;
GeneralPageHandler.call(this, this.args);
}
SpecificPageHandler.prototype.eventHandlers = function() {
GeneralPageHandler.eventHandlers.call(this);
$('#Select').change(function() {
//Do something
});
$('#OK').click(function() {
//Do something that might be different to the previous click handler
}
}
For the most part this allows me to re-use event handlers for common page elements, but I have found I end up with multiple handlers being defined for the same elements, depending on the specific page's purpose. I also find that I'm sometimes 'inheriting' event handlers which I don't particularly need on a specific page, but I think this might be more my misuse of the prototype model than anything else.
Does this seem a sensible way to go about re-using event handlers? Are there any ways that I could make this pattern more robust?