te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Drag 'n Drop Events firing multiple times - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Drag 'n Drop Events firing multiple times - Stack Overflow

programmeradmin3浏览0评论

I am working on a webapp with drag 'n drop functionality. Up to now I used basic HTML5 Dragging but now I switched to using the library interact.js.

I don't know if my problem is specific to this library or of more general kind: Events when dragging and dropping usually fire multiple times (if I have watched it correctly, it also seems to always be exactly 4 times, but no guarantee on that).

I am also using Vue.js and this is my code:

<template>
    <v-card
      elevation="0"
      :id="id"
      class="board device-dropzone"
    >
        <slot class="row"/>
        <div
         Drop Card here
        </div>
    </v-card>
</template>

In the slot, an image and div with text get added. Also this is the script:

<script>
import interact from 'interactjs';

export default {
  name: 'Devices',
  props: ['id', 'acceptsDrop'],
  data() {
    return {
      extendedHover: false,
      hoverEnter: false,
      timer: null,
      totalTime: 2,
    };
  },
  methods: {
    resetHover() {
      alert('reset');
    },
    drop(e) {
      let wantedId = e.relatedTarget.id.split('-')[0];
      console.log(wantedId);
      console.warn(e.target);
      e.target.classList.remove('hover-drag-over');
      this.extendedHover = false;
      console.log('-------------dropped');
      console.warn('dropped onto device');
      this.$emit('dropped-ponent', cardId);
      e.target.classList.remove('hover-drag-over'); */
    },
    dragenter() {
      console.log('------------dragenter');
      this.hoverEnter = true;
        setTimeout(() => {
          this.extendedHover = true;
          console.log('extended hover detected');
        }, 2000);
      } */
      this.timerID = setTimeout(this.countdown, 3000);
    },
    dragover(e) {
      if (this.acceptsDrop) {
        e.target.classList.add('hover-drag-over');
      }
    },
    dragleave(e) {
      if (this.acceptsDrop) {
        clearInterval(this.timer);
        this.timer = null;
        this.totalTime = 2;
        e.target.classList.remove('hover-drag-over');
        this.extendedHover = false;
        this.hoverEnter = false;
        console.log('................');
        console.warn(this.extendedHover);
        // this.$emit('cancel-hover');
      }
    },
    countdown() {
     console.log('!!!!!!!!!!!!!!!!!!!!');
     if (this.hoverEnter === true) {
        this.extendedHover = true;
        console.log('-------------------');
        console.warn(this);
        console.warn(this.extendedHover);
        this.$emit('long-hover');
      } 
    },
  },
  mounted() {
    // enable draggables to be dropped into this
    const dropzone = this;
    interact('.device-dropzone').dropzone({
      overlap: 0.9,
      ondragenter: dropzone.dragenter(),
      ondrop: function (event) {
        dropzone.drop(event);
      },
    })
  },
};
</script>

The draggable ponent is this one:

<template>
  <v-card
    class="primary draggable-card"
    :id = "id"
    :draggable = "false"
    @dragover.stop
    ref="interactElement"
  >
    <slot/>
  </v-card>

With the script:

<script>
import interact from 'interactjs';

export default {
  props: ['id', 'draggable'],
  data() {
    return {
      isInteractAnimating: true,
      position: { x: 0, y: 0 },
    };
  },
  methods: {
    /* dragStart: (e) => {
      e.stopPropagation(); // so dragStart of ParentBoard does not get triggered as well
      // eslint-disable-next-line
      const target = e.target;
      e.dataTransfer.setData('card_id', target.id);
      e.dataTransfer.setData('type', 'widget');
      // for some delay
      setTimeout(() => {
        console.log('started dragging');
      }, 0);
    }, */
    dragEndListener: (event) => {
      console.warn('+++++++++++++++++++++++++++');
      // console.warn(event.currentTarget.id);
      if (document.getElementById(event.currentTarget.id)) {
        event.currentTarget.parentNode.removeChild(event.currentTarget);
      }
    },
    dragMoveListener: (event) => {
      /* eslint-disable */
      var target = event.target;
      // keep the dragged position in the data-x/data-y attributes
      const xCurrent = parseFloat(target.getAttribute('data-x')) || 0;
      const yCurrent = parseFloat(target.getAttribute('data-y')) || 0;
      const valX = xCurrent + event.dx;
      const valY = yCurrent + event.dy;
      // translate the element
      event.target.style.transform =
        `translate(${valX}px, ${valY}px)`

      // update the postion attributes
      target.setAttribute('data-x', x);
      target.setAttribute('data-y', y);
    }
    /* eslint-enable */
  },
  mounted() {
    const element = this.$refs.interactElement;
    console.log(element);
    // interact(element).draggable({
    const ponent = this;
  interact('.draggable-card')
    .draggable({ 
      manualStart: true,
      onmove: ponent.dragMoveListener,
      onend:ponent.dragEndListener,
    })
    .on('move', function (event) {
      var interaction = event.interaction;
      // if the pointer was moved while being held down
      // and an interaction hasn't started yet
      if (interaction.pointerIsDown && !interaction.interacting()) {
        var original = event.currentTarget;
        // create a clone of the currentTarget element
        const clone = event.currentTarget.cloneNode(true);
        clone.id = clone.id + "-clone"; 
        clone.classname += " dragged-clone";
        // insert the clone to the page
        document.body.appendChild(clone);

        clone.style.opacity = 0.5;

        // start a drag interaction targeting the clone
        interaction.start({ name: 'drag' },
          event.interactable,
          clone);
      } 
    })
    .on('end', function (event) {
      console.error('end drag');
    });
  },
  /* eslint-enable */
};
</script>

In general the dragging and dropping works. But I don't get why e.g. the drop-event would trigger four times when only dropping a single card. Can anybody help me with this?

I am working on a webapp with drag 'n drop functionality. Up to now I used basic HTML5 Dragging but now I switched to using the library interact.js.

I don't know if my problem is specific to this library or of more general kind: Events when dragging and dropping usually fire multiple times (if I have watched it correctly, it also seems to always be exactly 4 times, but no guarantee on that).

I am also using Vue.js and this is my code:

<template>
    <v-card
      elevation="0"
      :id="id"
      class="board device-dropzone"
    >
        <slot class="row"/>
        <div
         Drop Card here
        </div>
    </v-card>
</template>

In the slot, an image and div with text get added. Also this is the script:

<script>
import interact from 'interactjs';

export default {
  name: 'Devices',
  props: ['id', 'acceptsDrop'],
  data() {
    return {
      extendedHover: false,
      hoverEnter: false,
      timer: null,
      totalTime: 2,
    };
  },
  methods: {
    resetHover() {
      alert('reset');
    },
    drop(e) {
      let wantedId = e.relatedTarget.id.split('-')[0];
      console.log(wantedId);
      console.warn(e.target);
      e.target.classList.remove('hover-drag-over');
      this.extendedHover = false;
      console.log('-------------dropped');
      console.warn('dropped onto device');
      this.$emit('dropped-ponent', cardId);
      e.target.classList.remove('hover-drag-over'); */
    },
    dragenter() {
      console.log('------------dragenter');
      this.hoverEnter = true;
        setTimeout(() => {
          this.extendedHover = true;
          console.log('extended hover detected');
        }, 2000);
      } */
      this.timerID = setTimeout(this.countdown, 3000);
    },
    dragover(e) {
      if (this.acceptsDrop) {
        e.target.classList.add('hover-drag-over');
      }
    },
    dragleave(e) {
      if (this.acceptsDrop) {
        clearInterval(this.timer);
        this.timer = null;
        this.totalTime = 2;
        e.target.classList.remove('hover-drag-over');
        this.extendedHover = false;
        this.hoverEnter = false;
        console.log('................');
        console.warn(this.extendedHover);
        // this.$emit('cancel-hover');
      }
    },
    countdown() {
     console.log('!!!!!!!!!!!!!!!!!!!!');
     if (this.hoverEnter === true) {
        this.extendedHover = true;
        console.log('-------------------');
        console.warn(this);
        console.warn(this.extendedHover);
        this.$emit('long-hover');
      } 
    },
  },
  mounted() {
    // enable draggables to be dropped into this
    const dropzone = this;
    interact('.device-dropzone').dropzone({
      overlap: 0.9,
      ondragenter: dropzone.dragenter(),
      ondrop: function (event) {
        dropzone.drop(event);
      },
    })
  },
};
</script>

The draggable ponent is this one:

<template>
  <v-card
    class="primary draggable-card"
    :id = "id"
    :draggable = "false"
    @dragover.stop
    ref="interactElement"
  >
    <slot/>
  </v-card>

With the script:

<script>
import interact from 'interactjs';

export default {
  props: ['id', 'draggable'],
  data() {
    return {
      isInteractAnimating: true,
      position: { x: 0, y: 0 },
    };
  },
  methods: {
    /* dragStart: (e) => {
      e.stopPropagation(); // so dragStart of ParentBoard does not get triggered as well
      // eslint-disable-next-line
      const target = e.target;
      e.dataTransfer.setData('card_id', target.id);
      e.dataTransfer.setData('type', 'widget');
      // for some delay
      setTimeout(() => {
        console.log('started dragging');
      }, 0);
    }, */
    dragEndListener: (event) => {
      console.warn('+++++++++++++++++++++++++++');
      // console.warn(event.currentTarget.id);
      if (document.getElementById(event.currentTarget.id)) {
        event.currentTarget.parentNode.removeChild(event.currentTarget);
      }
    },
    dragMoveListener: (event) => {
      /* eslint-disable */
      var target = event.target;
      // keep the dragged position in the data-x/data-y attributes
      const xCurrent = parseFloat(target.getAttribute('data-x')) || 0;
      const yCurrent = parseFloat(target.getAttribute('data-y')) || 0;
      const valX = xCurrent + event.dx;
      const valY = yCurrent + event.dy;
      // translate the element
      event.target.style.transform =
        `translate(${valX}px, ${valY}px)`

      // update the postion attributes
      target.setAttribute('data-x', x);
      target.setAttribute('data-y', y);
    }
    /* eslint-enable */
  },
  mounted() {
    const element = this.$refs.interactElement;
    console.log(element);
    // interact(element).draggable({
    const ponent = this;
  interact('.draggable-card')
    .draggable({ 
      manualStart: true,
      onmove: ponent.dragMoveListener,
      onend:ponent.dragEndListener,
    })
    .on('move', function (event) {
      var interaction = event.interaction;
      // if the pointer was moved while being held down
      // and an interaction hasn't started yet
      if (interaction.pointerIsDown && !interaction.interacting()) {
        var original = event.currentTarget;
        // create a clone of the currentTarget element
        const clone = event.currentTarget.cloneNode(true);
        clone.id = clone.id + "-clone"; 
        clone.classname += " dragged-clone";
        // insert the clone to the page
        document.body.appendChild(clone);

        clone.style.opacity = 0.5;

        // start a drag interaction targeting the clone
        interaction.start({ name: 'drag' },
          event.interactable,
          clone);
      } 
    })
    .on('end', function (event) {
      console.error('end drag');
    });
  },
  /* eslint-enable */
};
</script>

In general the dragging and dropping works. But I don't get why e.g. the drop-event would trigger four times when only dropping a single card. Can anybody help me with this?

Share Improve this question edited Jun 9, 2020 at 14:32 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 9, 2020 at 13:27 NotARobotNotARobot 5153 gold badges12 silver badges28 bronze badges 1
  • I am debugging a similar issue with the interactjs library. ondrop event fires twice, then four times, then eight. Did you find the issue in the end? – bigsee Commented Jul 9, 2020 at 15:10
Add a ment  | 

1 Answer 1

Reset to default 17

I was facing a similar issue using the same framework and library. Since there was some logic based on the event firing, it was breaking my app when it fired multiple times.

I suspected that the issue was related to bubbling of events.

The solution in my case was therefore to add event.stopImmediatePropagation() inside my drop(event) handler.

As noted in the referenced article, one should take care when stopping event bubbling that it doesn't have unforeseen consequences elsewhere.

发布评论

评论列表(0)

  1. 暂无评论