我有一个<draftable-input>
开始增长的组件。它有四种不同的“类型”:文本、文本区域、 slider 、所见即所得。这是教科书般的继承案例。
核心功能 - 让用户将输入编辑为“草稿”,然后保存或放弃他们的更改 - 在所有四种类型中都很常见。唯一的区别是模板的单个部分。
目前我这样使用它:
{{#draftable-input
type='wysiwyg'
...}}
{{#draftable-input
type='textarea'
...}}
等等。组件本身大约有 100 行。我有一些 CPS 和一种基于 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'),
其他约 85 行是通用的。
模板大约有 60 行,其中大约一半如下所示:
{{#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}}
另一半是通用的。
所以,我的蜘蛛侠感觉很兴奋,将其重构为四个独立的组件。一个抽象的 DraftableBase,以及四个特化。这非常适合我的 JS 代码 - 我可以删除切换类型的代码,并且每个子类只需要指定其选择器:
export default DraftableBase.extend({
selector: '.redactor-editor'
});
问题是模板。如何在每个子类中共享 30 行?据我所知,没有办法对子类进行“模板继承”之类的操作。所以,我不知道该怎么办。如果我进行子类化,我就可以放弃所有荒谬的类型切换代码,但随后我将复制很多 Handlebars。
建议?谢谢!
最佳答案
不存在模板继承之类的东西,但您可以使用部分重构代码。您需要动态生成部分名称
App.MyComponentComponent = Ember.Component.extend({
partialName: function() {
return 'my-component-partial/' + this.get('type');
}.property('type')
});
模板中每个类型的不同位置
<script type="text/x-handlebars" data-template-name="index">
{{my-component type="textarea"}}
<hr />
{{my-component type="input"}}
</script>
<script type="text/x-handlebars" data-template-name="components/my-component">
common things
{{partial partialName}}
common things
</script>
<script type="text/x-handlebars" data-template-name="my-component-partial/textarea">
<p>text area here</p>
</script>
<script type="text/x-handlebars" data-template-name="my-component-partial/input">
<p>input here</p>
</script>
演示:http://jsbin.com/gijecukuxu/1/
当然,您也可以创建基本 View 和 subview 。
关于ember.js - Ember 中是否可以实现类似模板继承的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29310995/