If you’ve ever done any iOS or Mac development you’re probably pretty familiar with the delegation pattern. If you’ve never set foot in Cocoa land you’ve probably never heard about this (or at least not used it). Basically delegation is a way of specializing an object and removing certain “business logic” from it. For example, take the
UITableView on iOS. That’s the class responsible for displaying all those lists you see on the iPhone. It has a very “simple” mission: render a list of item (and manage scrolling, view reuse etc). An instance of
UITableView knows nothing about the data it displays, or how it should be displayed. This is all up to the
delegate to figure out. Ie. the table view instance will query the
dataSource for data and views to render.
The data source protocol defines a number of methods that a table view data source must or can implement. So, the table view asks the data source “Hey, how many rows should I draw?”, “How high are the cells for each row?” and “Could I please have the cell for row 5 in section 2”. Et cetera. (Nitpickers need not point out the fact that I took the data source instead of the actual delegate as an example. IMO the data source is a delegate, just another kind. Also made for a better example.)
This makes for very clean separation of responsibilities. The table view don’t have to know anything about where the data comes from. Which makes it very easy to reuse the table view itself. Say you’re building a Twitter client. There are many places you would show a timline, profile, main feed, list. All of them look the same, but the data comes from different places.
Kind of a rambly and weird post that didn’t really go anywhere. I just feel like delegation could be a handy pattern that should be used more on the web. Instead of having a jQuery-plugin that just takes a
ul-element already in the DOM you could have a component that acts upon a model.