emberjs/ember.js — Issue #291: Allow programmatic control of named childView's constructor
Author: trek
Created: 2011-12-22 18:21:25+00:00
State: open

Thought I'd float this pattern for comments before submitting code.

Occasionally I find myself writing several similar view classes whose primary difference is the class (in the object sense, not css) of a child view or two. A contrived example for discussion: two overlays, one used to display a photo, one used to display error messages.

// abstract class, never instantiated
App.Overlay = SC.View.extend({
classNames: ['overlay'],
click: function(){
this.set('isVisible', false);
}
});

App.PhotoOverlay = App.Overlay.extend({
templateName: 'photo-overlay',
photoBinding: 'App.photos.current',
});

App.ErrorOverlay = App.Overlay.extend({
templateName: 'error-overlay',
errorBinding: 'App.error'
});

This isn't terribly onerous because the template of each Overlay subclass is small and entirely overwritten. For more complex templates it's easy to stray into cut and paste programming territory. Image two autocomplete textfields whose only difference is the itemViewClass you want to apply to the #collection of found search terms. You end up reproducing 95% of a slightly complex template with multiple child views and structural markup to customize a single property.

Piggypacking on handlebars support for properties like viewName and itemViewClass, I've found that being able specificy child view classes programmatically has cut down on lots of template redundancy:

App.PhotoOverlay = App.Overlay.extend({
contentsViewClass: App.PhotoView,
photoBinding: 'App.photos.current'
});

App.ErrorOverlay = App.Overlay.extend({
contentsViewClass: App.ErrorMessage,
errorBinding: 'App.error'
});

But I'd be interested in hearing whether this has been a problem other people have encountered much and strategies they've used.