问题
Based on this question.
I'm moving from RequireJS to browserify (together with babelify) and try to rewrite my current modules to classes. For each of my RequireJS modules I have a method called eventHandler which handles all general module specific events. Now when I extend a class, the parent class calls the subclass`s eventHandler method which leads to invoking the method twice.
There's another problem with my current code, though. I've also two methods on several modules to bind and unbind events. The site I'm working on is a responsive site which shares the same JS across all device sizes. On some screen sizes (breakpoints) I want to bind some specific events, on others I mustn't (or even unbind them when coming from another breakpoint). So a typical module would look more or less like this:
'use strict';
let specificEventsBound = false;
class Tooltip {
constructor() {
this.eventHandler();
}
eventHandler() {
// bind general events across all breakpoints
}
bindSpecificEvents() {
// bind breakpoint specific events
specificEventsBound = true;
}
unbindSpecificEvents() {
// unbind breakpoint specific events
specificEventsBound = false;
}
checkBreakpoint() {
if(someBreakpoint) {
this.bindSpecificEvents();
} else {
this.unbindSpecificEvents();
}
}
}
module.exports = Tooltip;
When I now extend this class and implement a checkBreakpoint with a different someBreakpoint in the subclass, the bindSpecificEvents and unbindSpecificEvents will still get called when the super methods get invoked. I think I have to change how I'm handling the events right now... Could you suggest me on how to properly handle this? Perhaps a separate class just for event handling with registering and detaching methods?
回答1:
When I now extend this class and implement a
checkBreakpointwith a different someBreakpoint in the subclass, thebindSpecificEventsandunbindSpecificEventswill still get called when thesupermethods get invoked.
You may have a misunderstanding here. Even in superclass code, this.checkBreakpoint will look up the checkBreakpoint property on the object, find it on the object's immediate prototype (the subclass's), and call that version of checkBreakpoint.
Here's a simpler example (live copy on Babel's REPL):
class Base {
constructor() {
this.method1();
}
method1() {
this.method2();
}
method2() {
console.log("Base#method2");
}
}
class Derived extends Base {
method2() {
console.log("Derived#method2");
}
}
new Derived;
Output:
Derived#method2
Note how the call in Base#method1 to this.method2 calls Derived#method2, not Base#method2. This is vital to polymorphism.
来源:https://stackoverflow.com/questions/33982062/event-handling-with-subclasses