3 ms·
I work with objects that have immediate value - e.g., a form will be an object that has a reference to fields of interest, and member methods that listen to for
by warfangle 18y ago
I work with objects that have immediate value - e.g., a form will be an object that has a reference to fields of interest, and member methods that listen to form events to achieve validation, et cetera. I keep DOM elements as instance variables, because it's faster to access them that way than with selector engines. It also neatly separates my behavior - the JavaScript - from my presentation. If another piece of the page's script layer needs to listen to my form object, it can subscribe to the events that it publishes.
Basically, I treat DOM elements as the display portion of an object, and if another object needs to change it, it can fire an event. Keeps things nice and loosely coupled. And I typically keep any methods that update the DOM in a separate method - keeps everything nice and organized...
It's an interesting topic, and one that probably needs a little more exposition than this.
- sfioritto 18y agoThis seems like a clean approach and one that I've heard before. I now build function generators that wrap functionality around passed in elements and then register these functions with events -- so basically what you are doing except with closures instead of objects. I've found this approach useful where I'd prefer not to use a CSS selector over and over again. My suspicion is that these problems have been solved already by programmers creating traditional event-driven GUI applications. This is unfortunately something I have no experience in so I can only guess that there is some overlap in these problem domains.