Ember components and the delegation pattern


#1

I’ve been studying Cocoa and Sproutcore recently, at least partially to understand the design decisions in Ember a little bit better. I noticed the delegation design pattern is used prominently in Cocoa and Sproutcore also has support for it (I’m not sure the degree to which it is used). This pattern seems particularly useful for allowing a generic reusable object (like an Ember Component) to provide support for one or more hooks back into application specific code via a Delegate object.

I know that Ember Components support sending actions back to the target object via the sendAction API and in that manner can send messages back to application specific code. However, another use of delegation besides sending messages back to the application is to allow application specific code to impact the behavior of the component based on return values from messages that are sent to the delegate. And, sendAction doesn’t currently return a value.

As an example of where this could be useful, consider the example of TableView given by the Cocoa guides. One of the methods the delegate can implement is selectionShouldChangeInTableView. According to the docs:

This method is usually implemented when it’s necessary to perform validation on editing of a row before allowing the row selection to change.

For example, if the user is editing a row in the table view and the content of that row doesn’t meet the required criteria, the delegate should return NO from this method to prevent the user from changing the selection. If the action was denied, this method is responsible for telling users why the selection change was disallowed and what action they can take to rectify the situation. By default, this method returns YES, which allows the selection to be changed.

I could see this behavior being immensely useful if someone were to try and implement an Ember Table Component that behaved similarly to the Cocoa TableView. The component author could come up with their own ad hoc solution (expects to have a particular variable passed in and calls methods on that variable, if they exist). But this pattern feels so valuable and, I suspect, common that I wonder the API’s for handling it should be baked into the framework.

Is there a reason it wasn’t ported from Sproutcore to Ember? Does anyone else think this might be a valuable addition to the Ember Component API?

Here’s the blog post about delegation in sproutcore, for those that are interested.


#2

I’m not 100% sure it’s applicable here but I’ve solved a similar problem by using promises. The component will send an action and pass along a promise, and the controller will resolve the promise with the retrieved value.