如何识别我的Polymer.dart组件是否仍然是document.activeElement?

Nik*_*raf 4 dart polymer dart-polymer

我有一个CustomPassword组件,并希望提供一种方法isActive,允许您检索组件是否仍然是此网站上的活动元素.

示例代码:

custom_password.html

<polymer-element name="custom-password">
  <template>
    <div>Other things here</div>
    <input id="password-field" type="password" value="{{value}}">
  </template>
  <script type="application/dart" src="custom_password.dart"></script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

custom_password.dart

import 'package:polymer/polymer.dart';

@CustomTag('custom-password')
class CustomPassword extends PolymerElement {

  @published
  String value;

  CustomPassword.created() : super.created() {
  }

  bool isActive() {
    // TODO figure out if the CustomPassword element is still active.
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

Nik*_*raf 7

Polymer Group的帮助下,我能够提出一个解决方案:

对于具有shadow DOM支持的浏览器,它通过将hashCode document.activeElement与组件hashCode 进行比较而开箱即用.

对于没有shadow DOM支持的浏览器,密码字段将是活动元素.这里的技巧是包装document.activeElement,以便将它与包装进行比较passwordField.

例:

custom_password.dart

import 'package:polymer/polymer.dart';
import 'dart:html';
import 'dart:js' as js;

@CustomTag('custom-password')
class CustomPassword extends PolymerElement {

  @published
  String value;

  CustomPassword.created() : super.created() {
  }

  bool isActive() {
      var passwordField = $['password-field'];
      var activeElement = js.context.callMethod('wrap', [document.activeElement]);

      // For Browsers with shadow DOM support the shadowRoot.host matches while
      // for Browsers without shadow DOM support the password field match.
      if (activeElement.hashCode != hashCode &&
          activeElement.hashCode != passwordField.hashCode) {
        return false;
      } else {
        return true;
      }
  }
}
Run Code Online (Sandbox Code Playgroud)