gpt4 book ai didi

ember.js - 在 Ember 中是否可以实现模板继承?

转载 作者:行者123 更新时间:2023-12-02 06:08:32 25 4
gpt4 key购买 nike

我有一个 <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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com