vendredi 27 mars 2015

Is something like template inheritance possible in Ember?

I have a <draftable-input> component that's starting to grow. It has four different "types": text, textarea, slider, wysiwyg. This is a textbook case of inheritance.


The core functionality - letting the user edit the input as a 'draft' and then save or discard their changes - is common among all four types. The only difference is a single portion of the template.


Currently I use it like this:



{{#draftable-input
type='wysiwyg'
...}}

{{#draftable-input
type='textarea'
...}}


and so on. The component itself is ~100 lines. I some CPS and a method that do different things based on type:



isWysiwyg: Ember.computed.equal('type', 'wysiwyg'),
isSlider: Ember.computed.equal('type', 'slider'),
isTextarea: Ember.computed.equal('type', 'textarea'),
isText: Ember.computed.equal('type', undefined),

selector: function() {
var selector;
switch (this.get('type')) {
case 'wysiwyg':
selector = '.redactor-editor';
break;
case 'textarea':
selector = 'textarea';
break;
default:
selector = 'input'
break;
}

return selector;
}.property('type'),


The other ~85 lines are generic.


The template is ~60 lines, with about half of it looking like this:



{{#if isWysiwyg}}
{{redactor-input value=copy
buttons=buttons
placeholder=placeholder
escape-press='cancel'
errorMessage=errorMessage}}
{{/if}}

{{#if isText}}
{{input value=copy
class='form-control'
placeholder=placeholder
escape-press='cancel'}}
{{/if}}


and the other half is generic.


So, my spidey senses are tingling to refactor this into four separate components. One abstract DraftableBase, and the four specializations. This works perfect for my JS code - I'd get to delete the code that switches on type, and each subclass would simply need to specify its selector:



export default DraftableBase.extend({
selector: '.redactor-editor'
});


The problem is, the templates. How can I share the 30 lines across each subclass? As far as I know, there's no way to do something like "template inheritance" with subclasses. So, I don't know what to do. If I subclass, I get to drop all the ridiculous type-switching code, but then I'll be duplicating a lot of Handlebars.


Suggestions? Thanks!





Aucun commentaire:

Enregistrer un commentaire