聚合物:检测自定义元素外部的单击

时间:2016-03-12 04:50:33

标签: polymer polymer-1.0

我有一个自定义元素,想要检测它之外的点击次数。例如

<dom-module id="simple-element">



<style>
  </style>

  <template>
    <content></content>
  </template>

</dom-module>

<script>
  (function() {
    Polymer({
      is: 'simple-element',
      listeners: {
        'tap': 'regularTap'
      },
      regularTap: function() {
        console.log("i was tapped");
      }
    });
  })();
</script>

是否有一个我可以收听的事件会告诉我用户何时点击了该元素?感谢。

4 个答案:

答案 0 :(得分:2)

修改代码以使其真正起作用:

var that = this;

window.addEventListener("click", function(e){
    var target = e.target;

    while (target != that && target != document.body) {
        target = Polymer.dom(target).node.parentElement;
    }

    if (target == that) {
         console.log("inside element");
    } else {
         console.log("outside element");
    }
});

答案 1 :(得分:1)

您可以使用以下行为:

    <script>
      /** @polymerBehavior Polymer.HarleyClickOutsideBehavior */
      Polymer.HarleyClickOutsideBehavior = {

        ready: function () {
          // bind listener method
          this.clickOutsideListenerBinded = this._clickOutsideListener.bind(this)
        },

        detached: function () {
          this._clickOutsideUnlisten()
        },

        clickOutsideListen: function () {
          // run this method to start listening
          this._clickOutsideUnlisten()
          window.addEventListener('click', this.clickOutsideListenerBinded, false)
        },

        _clickOutsideUnlisten: function () {
          window.removeEventListener('click', this.clickOutsideListenerBinded, false)
        },

        _clickOutsideListener: function (ev) {
          // check if the user has clicked on my component or on my children
          var isOutside = !ev.path.find(function (path) {
            return path === this
          }.bind(this))
          if (isOutside) {
            this.onClickOutside()
            this._clickOutsideUnlisten()
          }
        },

        onClickOutside: function () {
          // overwrite this method to be notified
        }

      }
    </script>

答案 2 :(得分:0)

这些方面应该做你想做的事情:

.video-js

答案 3 :(得分:0)

我发现一个更简单的解决方案尚未在所有浏览器上进行过测试,但这是有道理的。因此,我向窗口添加了一个全局侦听器,并为自定义元素添加了一个侦听器。这样点击里面就会调用两者,点击外面只会调用global ..

listenToClickOutside() {
            this.addEventListener("click", thisClick, false);
            window.addEventListener("click", windowClick, false);

            var clicksInside = 0;
            var thisRef = this;

            function thisClick() {
                clicksInside++
            }

            function windowClick(event) {
                clicksInside--;
                if (clicksInside < 0) {
                    thisRef.removeEventListener("click", thisClick, false);
                    window.removeEventListener("click", windowClick, false);
                    // CLICKED outside
                }
            }
        }