Polymer 2中的模板,如何获取slot元素的上下文?

时间:2017-08-31 15:49:38

标签: javascript polymer shadow-dom

有没有办法从slot&#39?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>

1 个答案:

答案 0 :(得分:1)

由于您可以插入任何元素,即使是没有class ElementWithSlots { ... onSaveTap_(event) { this.dispatchEvent(new CustomEvent('saved', {bubbles: false})); } } 方法的元素,IMO也不是实现此目的的正确方法。聚合物严重依赖于介体模式。相反,您应该在单击保存按钮时触发事件,并在介体中对此事件执行操作(即,使用插槽和插槽元素实例化元素的组件。

<element-with-slots on-saved="onSavedEvent_">
  <slotted-element id="slotted" slot="foo"></slotted-element>
</element-with-slots>

然后,在你的调解员中:

onSavedEvent_ {
  this.$.slotted.actOnSave();
}

在你的调解员JS中:

    let screenWidth = UIScreen.main.bounds.size.width
    let viewWidth = 200.0
    let rect = CGRect(x: (Double)(screenWidth/2)-(Double)(viewWidth/2), y: 0, width: viewWidth, height: 40)