【发布时间】:2017-08-31 15:49:37
【问题描述】:
有没有办法从slot'ed 元素执行方法?我正在创建一个包含保存按钮的模板。理想情况下,模板应在单击自己的保存按钮时调用插槽内容(子项).save 方法。关于如何实现这一点的任何想法?
我尝试了以下模板:
<dom-module id="template-action-bar">
<template>
<style include="granite-bootstrap"></style>
<slot id="slot"></slot>
<div class="container flex-end-justified">
<button
hidden$=[[_isNotFn('next')]]
disabled$="[[!valid]]"
class="btn btn-primary"
on-click="_next"
>
Next (Save)
</button>
<button
hidden$=[[_isNotFn('back')]]
disabled$="[[!valid]]"
class="btn btn-primary"
on-click="_back"
>
Back (Undo)
</button>
</div>
</template>
<script>
class TemplateActionBar extends Organism {
static get is() {
return 'template-action-bar';
}
static get properties() {
return {
next: Function,
back: String
};
}
_isNotFn(fn) {
return this[fn] !== 'function';
}
_next() {
this.next();
}
_back() {
this.$.slot.undo();
}
}
window.customElements.define(TemplateActionBar.is, TemplateActionBar);
</script>
还有元素(它的简短版本):
<dom-module id="element-creation">
<template>
<template-action-bar
next="{{ save }}"
>
<!-- ....... -->
</template>
<script>
class ElementCreation extends Organism {
/* ****************** */
save() {
// FIRST ATTEMPT
console.log(this); // <- I want the scope of ElementCreation not template-action-bar
}
save() {
// SECOND TRY
return (function() {
console.log(this); // <- I want the scope of ElementCreation not template-action-bar
}());
}
}
window.customElements.define(ElementCreation.is, ElementCreation);
</script>
</dom-module>
【问题讨论】:
-
你试过什么?您有特定的代码相关问题吗?
-
我已经发布了一个例子。希望它有所帮助:)
标签: javascript polymer shadow-dom