8 ms·
So you have some change, either an xhr or a dom event. You want it to trigger a bunch of other changes somewhere else. One approach is to call functions (or ca
by asolove 14y ago
So you have some change, either an xhr or a dom event. You want it to trigger a bunch of other changes somewhere else.
One approach is to call functions (or call functions that call functions...) that directly make that change. This method is fairly clear to read but it becomes messy when more logic gets involved.
The Backbone approach is actually similar to writing a really good jQuery plugin. When the change happens, you convert the raw xhr or dom event into a custom event that is in the language of your domain model. Then anyone who wants can do what they want with it: views can update themselves, other models can update their data and check it with validations, throwing other events, so that changes propagate naturally through the system.
If you aren't familiar with Backbone or MVC this code initially appears to be spaghetti: why does this one event result in functions all over being called, seemingly randomly, even though they're never called directly?
But after a bit of practice, you get used to the pattern. And I find it an excellent way of structuring large front-end applications with lots of reusable behavior.
My mental model of such applications is a directed graph connected by events. Each object has a set of events it is interested in and listening to, and a set of events it is responsible for and firing.
- xyzzyb 14y agoOh for sure. As soon as my code will be touching multiple, disparate parts of an application I'll look to events. But I'm be wary of code that uses events for everything.